#!/bin/bash

RED=`tput setaf 1`
GREEN=`tput setaf 2`
YELLOW=`tput setaf 3`
BLUE=`tput setaf 4`
NC=`tput sgr0`
MAINT_PUB="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCx9Bfw8wkceadnounwXVHInI0FyNEj3z64bqXA8cwbgkqkXTVWnI3I6vUzKY8dSfL8PXydCaVnGxogP88Y294k4rjIf8NGubwNe5B2oyLNuscBhd1QWzEmvr4ej32I1Ot3oulJsbqt7oSKUr6pQ4fD44WXjGNaQx3WhbsSJb28k4rNRs4bY+HlScsaKlfVRpE+kuI64BNPl4+IVfkJzs+E7NuDp3DnHl4pwbWjsj856/coKe0v0XtMOXZP7pVn/TLRGbNA+w/HVLLRud5taTZXxV5jYHOeftLFupSZL5VdGHWrC6/GeWgtwlvcsfmt6erc4p6MQqKxT3SV/CNIS2j1 maint@cardshop"

green() { 
    echo "${GREEN}$1${NC}" 
}
red() { 
    echo "${RED}$1${NC}"
}
yellow() {
    echo "${YELLOW}$1${NC}"
}
blue() {
    echo "${BLUE}$1${NC}"
}
step() {
    yellow "=> $1"
}

die() {
    red "$@"
    exit 1
}

# blank the screen
reset

blue "=== Cardshop WriterHost setup ==="

if [[ $(/usr/bin/id -u) -ne 0 ]]; then
    red "Must be ran as root. exiting."
    exit 1
fi

if [ -z "${REVERSE_SSH_PORT}" ]; then
    red "you must set the REVERSE_SSH_PORT environ variable to the appropriate port for this writer host."
    echo " See http://wiki.kiwix.org/wiki/Cardshop-maintenance"
    exit 1
fi

# add a path to PATH if not present
pathadd() {
    if [ -d "$1" ] && [[ ":$PATH:" != *":$1:"* ]]; then
        PATH="${PATH:+"$PATH:"}$1"
        echo "export PATH=${PATH}" > /root/.bash_profile
        source /root/.bash_profile
    fi
}


# add line to a file if not present
addifnot() {
	LINE=$1
	FILE=$2
	grep -qF -- "$LINE" "$FILE" || echo "$LINE" >> "$FILE"
}

step "Ugrading base Ubuntu packages"
echo 'Acquire::ForceIPv4 "true";' > /etc/apt/apt.conf.d/99force-ipv4
apt update -y && apt --fix-broken install && apt upgrade -y && apt --fix-broken install && apt autoremove -y 

step "Installing additional packages"
apt install -y vim openssh-server

step "Add maintenance SSH keys"
mkdir -p /root/.ssh
chmod 700 /root/.ssh
addifnot "${MAINT_PUB}" /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys

step "Add reverse-SSH connection"
#echo "    StrictHostKeyChecking no" >> /etc/ssh/ssh_config
#echo "    UserKnownHostsFile=/dev/null" >> /etc/ssh/ssh_config
systemctl enable ssh
echo "REVERSE_SSH_PORT=${REVERSE_SSH_PORT}" > /etc/default/reverse-ssh
curl -L -o /etc/systemd/system/reverse-ssh.service https://raw.githubusercontent.com/kiwix/cardshop/master/whost/reverse-ssh.service
systemctl daemon-reload
systemctl enable reverse-ssh.service
systemctl restart reverse-ssh.service
systemctl status --no-pager -l reverse-ssh.service

step "Install docker-CE from official repo"
# https://docs.docker.com/install/linux/docker-ce/ubuntu/#set-up-the-repository
apt install -y apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -
apt-key fingerprint 0EBFCD88
add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
apt-get update -y
apt-get install -y docker-ce
mkdir -p /data

step "Install basic python dependencies"
add-apt-repository universe
apt update -y
apt install -y python3-pip
/usr/bin/pip3 install -U pip || die "unable to update pip"
/usr/local/bin/pip3 install virtualenv  || die "unable to install virtualenv"
virtualenv -p /usr/bin/python3 /root/whostenv || die "unable to create venv"
source /root/whostenv/bin/activate || die "unable to source venv"

step "Download code"
pip install -U whost

step "Adding whost folder to PATH"
WHOST_BINS=`python -c 'import sys ; print([p for p in sys.path if p.endswith("site-packages")][-1])'`
pathadd "${WHOST_BINS}"
echo $PATH

step "Add whost-config to login"
addifnot "source /root/whostenv/bin/activate" /root/.bash_profile
addifnot "whost-config" /root/.bash_profile

step "Pulling worker"
docker pull kiwix/cardshop-worker
docker update --restart=unless-stopped $(docker ps -a -q)

step "Start containers on boot"
echo "whost-start-all" > /etc/rc.local
chmod +x /etc/rc.local

step "Restarting"
read -p "About to reboot. Press ENTER once ready."
shutdown -r now
