#!/bin/bash

# Ensure the script is run as root
if [[ $EUID -ne 0 ]]; then
    echo "This script must be run as root"
    exit 1
fi

# Clean up potential duplicate repository entries
echo "Cleaning up duplicate repository entries..."
sed -i '/deb-multimedia/d' /etc/apt/sources.list
sed -i '/buster-backports/d' /etc/apt/sources.list.d/updates-security.list
sed -i '/buster-updates/d' /etc/apt/sources.list.d/updates-security.list
sed -i '/buster\/updates/d' /etc/apt/sources.list.d/updates-security.list

# Add the Debian Multimedia repository if it's not already present
echo "Adding the Debian Multimedia repository..."
echo "deb http://www.deb-multimedia.org buster main" | tee -a /etc/apt/sources.list

# Update package index with insecure repository option
echo "Updating package index..."
apt-get update -o Acquire::AllowInsecureRepositories=true

# Install the deb-multimedia-keyring to authenticate the packages
echo "Installing deb-multimedia-keyring..."
apt-get install -y --allow-unauthenticated deb-multimedia-keyring

# Update package index again after adding the keyring
echo "Updating package index again..."
apt-get update

# Import missing GPG keys
echo "Importing missing GPG keys..."
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 73A4F27B8DD47936 DC30D7C23CBBABEE A48449044AAD5C5D 4DFAB270CAA96DFA

# Add the 'buster-updates' and 'buster-security' repositories
echo "Adding buster-updates and buster-security repositories..."
echo "deb http://deb.debian.org/debian buster-updates main" | tee -a /etc/apt/sources.list.d/updates-security.list
echo "deb http://security.debian.org/debian-security buster/updates main" | tee -a /etc/apt/sources.list.d/updates-security.list

# Update the package index with the new repositories
echo "Updating package index with new repositories..."
apt-get update

# Manually download missing dependencies
echo "Downloading missing dependencies..."
wget -O /tmp/libcodec2-0.8.1_amd64.deb http://ftp.de.debian.org/debian/pool/main/c/codec2/libcodec2-0.8.1_0.8.1-2_amd64.deb

# Install downloaded dependencies
echo "Installing downloaded dependencies..."
apt-get install -y /tmp/libcodec2-0.8.1_amd64.deb

# Install missing dependencies manually
echo "Fixing broken packages..."
apt --fix-broken install -y

# Install a working version of tvheadend from deb-multimedia
echo "Installing tvheadend..."
apt-get install -y tvheadend

# Install `dialog` package if not installed
echo "Ensuring 'dialog' package is installed..."
apt-get install -y dialog

# Configure tvheadend vTuners
TVHEADEND_DEFAULTS="/etc/default/tvheadend"

NUM_TUNERS=$(dialog --title "SAT>IP vTuners Configuration" --inputbox "Please specify the number of SAT>IP vTuners to configure (1-8)" 8 50 3>&1 1>&2 2>&3 3>&-)

if ! [[ "$NUM_TUNERS" =~ ^[1-8]$ ]]; then
    dialog --title "Error" --msgbox "Please enter a valid number between 1 and 8." 6 50
    exit 1
fi

TVH_ARGS=""

for i in $(seq 1 "$NUM_TUNERS"); do
    while true; do
        IP_ADDRESS=$(dialog --title "SAT>IP vTuner IP Address" --inputbox "Enter the IP address for SAT>IP vTuner $i as specified in your order. (Format: x.x.x.x, where x is 0-255)" 8 70 3>&1 1>&2 2>&3 3>&-)

        # Validate IP address format (basic validation for IPv4 addresses)
        if [[ $IP_ADDRESS =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
            # Check each octet value is less than 256
            VALID_IP=true
            IFS='.' read -ra ADDR <<< "$IP_ADDRESS"
            for octet in "${ADDR[@]}"; do
                if [[ "$octet" -gt 255 ]]; then
                    VALID_IP=false
                    break
                fi
            done

            if $VALID_IP; then
                break # Exit the loop if IP is valid
            else
                dialog --title "Invalid IP Address" --msgbox "The IP address entered is invalid. Please enter a valid IPv4 address." 8 50
            fi
        else
            dialog --title "Invalid IP Address" --msgbox "The format of the IP address entered is incorrect. Please ensure it is a valid IPv4 address." 8 50
        fi
    done

    TVH_ARGS="${TVH_ARGS} --satip_xml http://${IP_ADDRESS}:8875/satip.xml"
done

dialog --title "Confirmation" --yesno "Are you sure you want to update tvheadend vTuner configuration with these options?\n\n$TVH_ARGS" 10 60

if [ $? -eq 0 ]; then
    # User confirmed, update the file
    echo "TVH_ARGS=\"$TVH_ARGS\"" | sudo tee "$TVHEADEND_DEFAULTS"
    dialog --title "Success" --msgbox "tvheadend vTuner configuration updated successfully." 6 50
else
    dialog --title "Cancelled" --msgbox "Operation cancelled." 6 50
fi

# Clear up dialog remnants
clear && service tvheadend restart
exit 0