#!/bin/bash

if [ -z "$*" ]; then echo "You need to provide your license key as an argument"; exit; fi

sudo apt-get update
sudo apt-get install unzip ca-certificates curl gnupg lsb-release -y

# python3-apt is required by the Heimdal package management bridge (bridge.py).
# It must be the distro-provided package — pip install will NOT work.
if ! dpkg -l python3-apt 2>/dev/null | grep -q "^ii"; then
    echo "[Heimdal] Installing python3-apt (required for package management bridge)..."
    sudo apt-get install python3-apt -y
fi

curl https://qa-linuxrepo.heimdalsecurity.com/pgp-key.public | sudo gpg --yes --dearmor -o /usr/share/keyrings/heimdal-keyring.gpg

echo "deb [arch=amd64 signed-by=/usr/share/keyrings/heimdal-keyring.gpg] https://qa-linuxrepo.heimdalsecurity.com/apt-repo stable main" | sudo tee /etc/apt/sources.list.d/heimdal.list

echo 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' > /etc/cron.d/heimdal-update
echo '0 */3 * * * root apt-get update && apt-get --only-upgrade install heimdal >> /var/log/heimdal-update.txt 2>&1' >> /etc/cron.d/heimdal-update

# Ubuntu 22.04 does not ship dotnet-runtime-10.0 in the default repos.
# Register the official .NET backports PPA so the heimdal deb's Depends: dotnet-runtime-10.0 resolves.
ubuntu_version=$(lsb_release -rs)
if [ "$ubuntu_version" = "22.04" ]; then
    sudo apt-get install -y software-properties-common
    sudo add-apt-repository -y ppa:dotnet/backports
fi

sudo apt-get update

# Write the license to a temp file so postinst can pick it up.
# apt-get does not pass stdin through to postinst scripts.
echo "$1" | sudo tee /tmp/heimdal-license.tmp > /dev/null

sudo apt-get install heimdal -y