#!/usr/bin/env bash
set -o errexit

# N4IRS 07/26/2017
# KK9ROB 04/02/2021
# WD6AWP 01/01/2023
# WD6AWP 07/20/2023 Add bookworm

#################################################
#                                               #
#  Add NEW AllStarLink Repository and GPG key   #
#                                               #
#################################################

# Install dependencies
DEPS="curl gpg lsb-release"
echo "Instlling needed dependencies: $DEPS"
apt install -y $DEPS

DISTRO=`lsb_release -sc 2> /dev/null`

BUILD=""
if [ "$1" = "testing" ] || [ "$1" = "devel" ]
then
	BUILD="-$1"
fi

# Prep and install the the repository
REPOBASE="http://apt.allstarlink.org/repos"
KEYSRC="$REPOBASE/repo_signing.gpg"
APTSRC="$REPOBASE/asl_builds$BUILD"

if [ "$DISTRO" = "bullseye" ] || [ "DISTRO" = "buster" ]; then
	KEYDEST="/usr/share/keyrings"
	curl -s $KEYSRC | gpg -o $KEYDEST/allstarlink-keyring.gpg --yes --dearmor
else
	test -f /usr/share/keyrings/allstarlink-keyring.gpg && \
		rm -f /usr/share/keyrings/allstarlink-keyring.gpg
	KEYDEST="/etc/apt/trusted.gpg.d"
	curl -s $KEYSRC | gpg -o $KEYDEST/allstarlink-keyring.gpg --yes --dearmor
	gpg --keyring $KEYDEST/allstarlink-keyring.gpg --export --armor > $KEYDEST/allstarlink-keyring.asc
fi

echo "deb [signed-by=$KEYDEST/allstarlink-keyring.gpg] $APTSRC $DISTRO main" > /etc/apt/sources.list.d/allstarlink.list

# Update the repositories
apt update

# print the installed repositories
echo "Installed repositories:"
apt-cache policy | grep http | awk '{print $2 " " $3}' | sort -u
