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

# N4IRS 10/25/2022

#################################################
#                                               #
#    Add DVSwitch Repository and gpg key        #
#                                               #
#################################################

if [[ $(/usr/bin/id -u) -ne 0 ]]; then
    echo "Not running as root"
    echo "either run as root or with sudo"
    exit
fi

echo ""
echo "Starting DVSwitch repository install"

distribution=buster

# Check if the os-release file exists and source it
if [ -f /etc/os-release ]; then
    . /etc/os-release
else
    echo "Error: /etc/os-release not found. Cannot determine distribution." >&2
    exit 1
fi

# Check if the OS codename is "bookworm"
if [ "$VERSION_CODENAME" = "bookworm" ]; then
    echo "Distribution is 'bookworm', exiting."
    exit 1
fi

# Continue with the rest of the script...

# INSTALL gnupg needed for gpg.key
[ ! -x "/usr/bin/gpg" ] && apt-get install gnupg -y

# Add the backport repository, if needed to install monit
if [ $(apt-cache policy monit | grep -c "Candidate: (none)") -eq 1 ] ; then
        # add repository
        printf "%s\n" "deb http://ftp.de.debian.org/debian buster-backports main" | tee /etc/apt/sources.list.d/buster-backports.list
fi

# INSTALL netstat needed by dvswitch.sh
[ ! -x "/bin/netstat" ] && apt-get install net-tools -y

# Check for rc.local and create if not found.
FILE="/etc/rc.local"
        if [ ! -f "$FILE" ] ; then
		echo '#!/bin/sh -e' > $FILE
		echo '' >> $FILE
		echo 'exit 0' >> $FILE
	   chmod +x $FILE
        fi

# Are the repos installed
# Should this test for buster too?
if [ -f /etc/apt/sources.list.d/dvswitch.list ]
then
    echo "The Repository file already exists, exiting"
    exit 0
fi

# Install the key and add the repo
echo "Adding DVSwitch repositories to existing system"
wget -O - http://dvswitch.org/DVSwitch_Repository/dvswitch.gpg.key 2>/dev/null | apt-key add - > /dev/null 2>&1

# replace above with this need more testing:
# curl -fsSL http://dvswitch.org/DVSwitch_Repository/dvswitch.gpg.key | sudo gpg --dearmor -o /usr/share/keyrings/dvswitch-keyring.gpg

echo "# Official DVSwitch repository" >/etc/apt/sources.list.d/dvswitch.list
echo "deb http://dvswitch.org/DVSwitch_Repository $distribution hamradio" >>/etc/apt/sources.list.d/dvswitch.list

# replace above with this:
# printf "%s\n" "deb http://dvswitch.org/DVSwitch_Repository $distribution hamradio" | tee /etc/apt/sources.list.d/dvswitch.list

echo "#" >>/etc/apt/sources.list.d/dvswitch.list

echo "download package information from all configured sources"
apt-get update --allow-releaseinfo-change > /dev/null 2>&1
apt-get update > /dev/null 2>&1

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

echo ""
echo "Finished DVSwitch repository install"

