#!/usr/bin/env bash

set -e

PROXY_SERVER="127.0.0.1:3128"
export http_proxy="http://${PROXY_SERVER}"
export https_proxy="https://${PROXY_SERVER}"

info() {
	echo -e "\033[33m$1\033[0m"
}

info "Checking resolv.conf"
# if /etc/resolv.conf has something, then save it
if [ -f "/etc/resolv.conf" ]; then
	old_resolv_conf="`cat /etc/resolv.conf`"
else
	old_resolv_conf=""
fi

cleanup() {
	# if we were able to create the apt upgrade configuration file, then remove it
	if [ -f "/etc/apt/apt.conf.d/99upgrade" ]; then
		info "Removing /etc/apt/apt.conf.d/99upgrade"
		rm -f "/etc/apt/apt.conf.d/99upgrade"
	fi

	if [ -f "/etc/apt/sources.list.d/stpc.list" ]; then
		info "Removing /etc/apt/sources.list.d/stpc.list"
		rm -f "/etc/apt/sources.list.d/stpc.list"
	fi

	if [ -f "/etc/resolv.conf" ]; then
		# if we found something in /etc/resolv.conf previously, then
		# save it otherwise, just remove the file because it was empty before
		if [ "${old_resolv_conf}" != "" ]; then
			info "Restoring old resolv.conf configuration"
			echo "${old_resolv_conf}" > "/etc/resolv.conf"
		else
			info "Removing /etc/resolv.conf because it was previously empty"
			rm -f "/etc/resolv.conf"
		fi
	fi
}
trap cleanup EXIT

setup_upgrade_configuration() {
	info "Setting up /etc/apt/apt.conf.d/99upgrade"
cat <<EOF > "/etc/apt/apt.conf.d/99upgrade"
Acquire::http::proxy "${http_proxy}";
Acquire::https::proxy "${https_proxy}";
Acquire::http::Timeout "5";
Acquire::ftp::Timeout "5";
EOF
}

setup_resolv_conf() {
	info "Setting up /etc/resolv.conf"
cat <<EOF > "/etc/resolv.conf"
nameserver 8.8.8.8
nameserver 8.8.4.4
EOF
}

setup_sources_list() {
	info "Setting up /etc/apt/sources.list.d/stpc.list"

	lines=()
	repos=("10.184.9.253" "10.180.9.253")
	for repo in "${repos[@]}"; do
		if wget -qO- -t 2 -T 2 "http://${repo}/pubkey.gpg" > /dev/null 2>&1; then
			info "Found available repo at ${repo}"
			lines+=("deb http://${repo}/repos/ubuntu/dosis/ stretch main")
		fi
	done

	echo "${lines[@]}"
cat <<EOF > "/etc/apt/sources.list.d/stpc.list"
`for l in "${lines[@]}"; do echo ${l}; done`
EOF
}

setup_gpg_key() {
	info "Configure GPG Key"
	if ! wget -qO- http://10.184.9.253/pubkey.gpg | apt-key add -; then
		if ! wget -qO- http://10.180.9.253/pubkey.gpg | apt-key add -; then
			exit 1
		fi
	fi
}

remount_filesystem_as_read_write() {
	info "Remounting filesystem as read/write"
	mount -o remount,rw /
}

stop_services() {
	info "Stopping STPC service"
	systemctl stop stpcd
	sleep 5
}

upgrade_packages() {
	info "Updating packages"
	apt-get update
	apt-get install stpc-services stpc-config stpc-printer-dkms
}

clean_apt_cache() {
	info "Cleaning package cache"
	apt-get clean
}

remount_filesystem_as_read_write
setup_upgrade_configuration
setup_resolv_conf
setup_sources_list
stop_services
upgrade_packages
clean_apt_cache

info "Packages Successfully Upgraded, Rebooting"
reboot
