#!/bin/sh

# This script installs the kamp-simon-shell-client and its repsitory.
# It currently works on Debian, Ubuntu and CentOS 7.
# - determine package manager (apt or yum)
# - get the public signing key
# - add the repo
# - update the repositories
# - seed config
# - install kamp-simon-shell-client
# If a server was configured:
# - sign system up
# - send all data to the server

# https://unix.stackexchange.com/a/10065
# Check if stdout is a terminal.
if [ -n "${TERM}" ] && [ -t 1 ]; then
    # See if it supports colors.
    ncolors=$(tput colors)
    if [ -n "${ncolors}" ] && [ "${ncolors}" -ge 8 ]; then
        # Define colors and typography.
        bold="$(tput bold)"
        underline="$(tput smul)"
        standout="$(tput smso)"
        normal="$(tput sgr0)"
        black="$(tput setaf 0)"
        red="$(tput setaf 1)"
        green="$(tput setaf 2)"
        yellow="$(tput setaf 3)"
        blue="$(tput setaf 4)"
        magenta="$(tput setaf 5)"
        cyan="$(tput setaf 6)"
        white="$(tput setaf 7)"
    fi
fi


# Check if run as root or with sudo.
if [ "$(id -u)" -ne 0 ]; then
    echo "${red}${bold}This script must be run as root or with sudo! Exiting!${normal}" 1>&2
    exit 1
fi


# Check witch platform to install on.
if command -v apt-get > /dev/null 2>&1; then
    MANAGER_TYPE="apt"
    export DEBIAN_FRONTEND=noninteractive
elif command -v yum > /dev/null 2>&1; then
    MANAGER_TYPE="yum"
else
    echo "${red}${bold}Neither apt-get nor yum available! Exiting!${normal}"
    exit 1
fi

echo "${bold}Installing with ${MANAGER_TYPE}.${normal}"


# Set some default values.
# These definitions first check if their variable hasn't already been set.

# The server to send to. (default: https://backend.kamp-simon:8443)
# [ -z "${SERVER}" ] && SERVER="https://backend.kamp-simon:8443"
# If $1 is not empty use it as the server.
[ -n "${1}" ] && SERVER="${1}"
# Allow insecure curl SSL connections? (default: false)
# IF SET TO true ALL SERVER CERTIFICATES WILL BE ALLOWED!
[ -z "${INSECURE}" ] && INSECURE=false
# Send data after installation? (default: false)
[ -z "${SEND_NOW}" ] && SEND_NOW=false
# Keep the cronjobs? (default: true)
[ -z "${INSTALL_CRON}" ] && INSTALL_CRON=true
# Keep the DPKG hooks? (default: true)
[ -z "${INSTALL_DPKG_HOOKS}" ] && INSTALL_DPKG_HOOKS=true
# Send Pre Shared Key? (default: empty string)
[ -z "${PSK}" ] && PSK=""


apt_get_key() {
    if command -v curl > /dev/null 2>&1; then
        DL_CMD="curl -fsSl https://mirror.kamp.de/kamp-simon/GPG-KEY-deb"
    elif command -v wget > /dev/null 2>&1; then
        DL_CMD="wget --quiet -O - https://mirror.kamp.de/kamp-simon/GPG-KEY-deb"
    else
        echo "${red}${bold}Neither curl nor wget available! Exiting!${normal}"
        exit 1
    fi

    eval "${DL_CMD}" | apt-key --keyring /etc/apt/trusted.gpg.d/kamp-simon.gpg add -
    RETVAL="${?}"

    if [ "${RETVAL}" -ne 0 ]; then
        echo "${red}${bold}Error while getting and adding key! Exiting!${normal}"
        exit 1
    fi
}

apt_add_repo() {
    if command -v curl > /dev/null 2>&1; then
        DL_CMD="curl -fsSl https://mirror.kamp.de/kamp-simon/kamp-simon.list"
    elif command -v wget > /dev/null 2>&1; then
        DL_CMD="wget --quiet -O - https://mirror.kamp.de/kamp-simon/kamp-simon.list"
    else
        echo "${red}${bold}Neither curl nor wget available! Exiting!${normal}"
        exit 1
    fi

    eval "${DL_CMD}" | tee /etc/apt/sources.list.d/kamp-simon.list
    RETVAL="${?}"

    if [ "${RETVAL}" -ne 0 ]; then
        echo "${red}${bold}Error while adding repo! Exiting!${normal}"
        exit 1
    fi
}

apt_update() {
    # Remove old repository list.
    if [ -e /etc/apt/sources.list.d/lusi.list ]; then
        echo "${bold}Removing old repository list from /etc/apt/sources.list.d/lusi.list.${normal}"
        rm -rf /etc/apt/sources.list.d/lusi.list
        echo "${green}${bold}Removed old repository list.${normal}"
    fi


    apt-get --quiet update
    RETVAL="${?}"

    if [ "${RETVAL}" -ne 0 ]; then
        echo "${red}${bold}Error while updating! Exiting!${normal}"
        exit 1
    fi
}

apt_seed() {
    if [ -n "${SERVER}" ]; then
        echo "kamp-simon-shell-client kamp-simon-shell-client/server string ${SERVER}" | debconf-set-selections
    fi
    echo "kamp-simon-shell-client kamp-simon-shell-client/insecure_curl boolean ${INSECURE}" | debconf-set-selections
    echo "kamp-simon-shell-client kamp-simon-shell-client/send_now boolean ${SEND_NOW}" | debconf-set-selections
    echo "kamp-simon-shell-client kamp-simon-shell-client/install_cron boolean ${INSTALL_CRON}" | debconf-set-selections
    echo "kamp-simon-shell-client kamp-simon-shell-client/install_dpkg_hooks boolean ${INSTALL_DPKG_HOOKS}" | debconf-set-selections
    echo "kamp-simon-shell-client kamp-simon-shell-client/psk string ${PSK}" | debconf-set-selections
}

apt_install() {
    apt-get --quiet install --yes kamp-simon-shell-client
    RETVAL="${?}"

    if [ "${RETVAL}" -ne 0 ]; then
        echo "${red}${bold}Error while installing! Exiting!${normal}"
        exit 1
    fi


    # Copy old config if available.
    if [ -e /etc/lusi/shell-client/shell-client.conf ]; then
        echo "${bold}Copying old config.${normal}"
        cp -v /etc/lusi/shell-client/shell-client.conf /etc/kamp-simon/shell-client/
        echo "${green}${bold}Copied old config.${normal}"
    fi


    # Copy old keys if available.
    if [ -e /etc/lusi/shell-client/shell-client.rsa ] && [ -e /etc/lusi/shell-client/shell-client.rsa.pub ]; then
        echo "${bold}Copying old keys.${normal}"
        cp -v /etc/lusi/shell-client/shell-client.rsa /etc/lusi/shell-client/shell-client.rsa.pub /etc/kamp-simon/shell-client/
        echo "${green}${bold}Copied old keys.${normal}"
    fi
}


yum_get_key() {
    rpm --import https://mirror.kamp.de/kamp-simon/GPG-KEY-rpm
    RETVAL="${?}"

    if [ "${RETVAL}" -ne 0 ]; then
        echo "${red}${bold}Error while getting and adding key! Exiting!${normal}"
        exit 1
    fi
}

yum_add_repo() {
    if command -v yum-config-manager > /dev/null 2>&1; then
        yum-config-manager --add-repo https://mirror.kamp.de/kamp-simon/kamp-simon.repo
        RETVAL="${?}"
    else
        if command -v curl > /dev/null 2>&1; then
            DL_CMD="curl -fsSl https://mirror.kamp.de/kamp-simon/kamp-simon.repo"
        elif command -v wget > /dev/null 2>&1; then
            DL_CMD="wget --quiet -O - https://mirror.kamp.de/kamp-simon/kamp-simon.repo"
        else
            echo "${red}${bold}Neither yum-config-manager nor curl nor wget available! Exiting!${normal}"
            exit 1
        fi

        eval "${DL_CMD}" | tee /etc/yum.repos.d/kamp-simon.repo
        RETVAL="${?}"
    fi

    if [ "${RETVAL}" -ne 0 ]; then
        echo "${red}${bold}Error while updating! Exiting!${normal}"
        exit 1
    fi
}

yum_update() {
    yum --assumeyes makecache
    RETVAL="${?}"

    if [ "${RETVAL}" -ne 0 ]; then
        echo "${red}${bold}Error while updating! Exiting!${normal}"
        exit 1
    fi
}

yum_seed() {
    if [ -n "${SERVER}" ]; then
        export SERVER="${SERVER}"
    fi
    export INSECURE="${INSECURE}"
    export SEND_NOW="${SEND_NOW}"
    export PSK="${PSK}"
}

yum_install() {
    yum install --assumeyes kamp-simon-shell-client
    RETVAL="${?}"

    if [ "${RETVAL}" -ne 0 ]; then
        echo "${red}${bold}Error while installing! Exiting!${normal}"
        exit 1
    fi
}


get_key() {
    if [ "${MANAGER_TYPE}" = apt ]; then
        apt_get_key
    elif [ "${MANAGER_TYPE}" = yum ]; then
        yum_get_key
    fi
}

add_repo() {
    if [ "${MANAGER_TYPE}" = apt ]; then
        apt_add_repo
    elif [ "${MANAGER_TYPE}" = yum ]; then
        yum_add_repo
    fi
}

update() {
    if [ "${MANAGER_TYPE}" = apt ]; then
        apt_update
    elif [ "${MANAGER_TYPE}" = yum ]; then
        yum_update
    fi
}

seed() {
    if [ "${MANAGER_TYPE}" = apt ]; then
        apt_seed
    elif [ "${MANAGER_TYPE}" = yum ]; then
        yum_seed
    fi
}

install() {
    if [ "${MANAGER_TYPE}" = apt ]; then
        apt_install
    elif [ "${MANAGER_TYPE}" = yum ]; then
        yum_install
    fi
}

# Get the public signing key.
echo "${bold}Getting and adding kamp-simon public signing key.${normal}"
get_key
echo "${green}${bold}Added kamp-simon public signing key.${normal}"


# Add repository list.
echo "${bold}Adding kamp-simon repository.${normal}"
add_repo
echo "${green}${bold}Added kamp-simon repository.${normal}"


# Update repositories.
echo "${bold}Updating repositories.${normal}"
update
echo "${green}${bold}Updated repositories.${normal}"


# Set configuration options.
# Uncomment to set them to the above variables, comment to use defaults from package.
echo "${bold}Seeding configuration options.${normal}"
seed
echo "${green}${bold}Seeded configuration options.${normal}"


# Install kamp-simon-shell-client.
echo "${bold}Installing kamp-simon-shell-client.${normal}"
install
echo "${green}${bold}"
echo "***************************************************"
echo "* kamp-simon-shell-client successfully installed. *"
echo "***************************************************"
echo "${normal}"


# Get effective server from config file.
EFFECTIVE_SERVER="$(if [ -e /etc/kamp-simon/shell-client/shell-client.conf ]; then . /etc/kamp-simon/shell-client/shell-client.conf && echo "${SERVER}"; fi)"

if [ -n "${EFFECTIVE_SERVER}" ]; then
    # Sign up.
    echo "${bold}Signing up at.${normal}"
    echo "${yellow}${bold}Errors with Response-Code 409 can be ignored.${normal}"
    kamp-simon-shell-client --sign-up
    RETVAL="${?}"
    if [ "${RETVAL}" -eq 0 ]; then
        echo "${green}${bold}Signed up.${normal}"
    elif [ "${RETVAL}" -eq 5 ]; then
        echo "${yellow}${bold}This client is already signed up. Continuing with installation.${normal}"
    else
        echo "${red}${bold}Error while signing up! Exiting!${normal}"
        exit 1
    fi


    # Send everything.
    echo "${bold}Sending all data.${normal}"
    kamp-simon-shell-client --all
    RETVAL="${?}"
    if [ "${RETVAL}" -eq 0 ]; then
        echo "${green}${bold}Sent all data.${normal}"
    else
        echo "${red}${bold}Error while sending all data! Exiting!${normal}"
        exit 1
    fi
else
    echo "${yellow}${bold}No Server given. Not signing up!${normal}"
fi


# Purge old client.
if [ "${MANAGER_TYPE}" = apt ] && dpkg -s lusi-shell-client > /dev/null 2>&1; then
    echo "${bold}Purging old lusi-shell-client.${normal}"
    apt-get --quiet purge --yes lusi-shell-client
    echo "${green}${bold}Purged old lusi-shell-client.${normal}"
fi
