#!/bin/bash


SERVER="https://packages.thincast.com"
REPO_KEY_FILE="thincast-package-2023.pgp"
CHANNEL="stable"
SOURCES_LIST="/etc/apt/sources.list.d/thincast-${CHANNEL}.list"
KEYRING_DIR="/etc/apt/keyrings"
REPO_KEY="${KEYRING_DIR}/${REPO_KEY_FILE}"

not_supported()
{
	echo "The system or architecture you are trying to install on is not supported."
	echo "See our documentation or contact https://thincast.com/contact us."
	exit 1
}

root_check()
{
	if [ $EUID != 0 ]; then
		echo "This script must be run as root"
		exit 1
	fi
}

check_old_install()
{
	if [ -f ${SOURCES_LIST} ];then
		echo "Sources list alreaady exists. Stopping"
		exit 1
	fi
	if [ -f /etc/apt/sources.list.d/thincast-*.list ];then
		echo "There is already another sources list for thincast installed in /etc/apt/sources.list.d/"
		echo "Remove this first"
		echo "Please note: when switching between channels (stable/beta/..) it's recommended to remove the packages before upgrading."
		exit 1
	fi
}

requirement_check()
{
	echo "Checking requirements"
	if ! command -v curl > /dev/null; then
		echo "Curl is not installed"
		echo "please run 'sudo apt-get install curl' to install"
		exit 1
	fi
}

install_repo_key()
{
	echo "Installing apt repository keys"

	# use /etc/apt/keyring as recommended by Debian
	# https://wiki.debian.org/DebianRepository/UseThirdParty
	if [ ! -d ${KEYRING_DIR} ];then
		mkdir ${KEYRING_DIR}
		chmod 0755 ${KEYRING_DIR}
	fi

	if [ ! -f ${REPO_KEY} ];then
		curl --silent --fail --fail-early -o ${REPO_KEY} ${SERVER}/${REPO_KEY_FILE}
		if [ $? -ne 0 ];then
			echo "Problem installing the repository key ${KEY}"
			exit 1
		fi
	fi
}

check_and_detect_os ()
{
	echo "Detecting OS and platform"
		if [ ! -f /etc/os-release ];then
		not_supported
	fi
	. /etc/os-release

	case "$ID" in
		"ubuntu"|"debian")
			;;
		*)
			not_supported
			;;
	esac

	case "$VERSION_CODENAME" in
	        "bullseye"|"bookworm"|"focal"|"jammy"|"noble"|"trixie")
			;;
		*)
			not_supported
	esac

	case "$(uname -m)" in
		"x86_64"|"i686")
			;;
		*)
			not_supported
	esac

}


apt_update()
{
	apt-get update &> /dev/null
}

configure_repo ()
{
	echo "deb [signed-by=${REPO_KEY}] http://packages.thincast.com/deb/${CHANNEL}/${VERSION_CODENAME} thincast main" > /etc/apt/sources.list.d/thincast-${CHANNEL}.list
}

if [ $# -gt 0 ];then
	case "$1" in
		"nightly"|"beta")
			CHANNEL=$1
			;;
					*)
			echo "Unsupported channel $1"
			exit 1
	esac
fi

root_check
check_old_install
check_and_detect_os
requirement_check
install_repo_key
configure_repo
apt_update
echo "Done. You can now install the Thincast application by with apt"
