#!/bin/bash
set -e

REP_ID="om7"
REPO_URL="https://deb.om7.com"
KEY_URL="$REPO_URL/$REP_ID.gpg.asc"
KEYRING="/usr/share/keyrings/$REP_ID-archive-keyring.gpg"
SOURCE_LIST="/etc/apt/sources.list.d/$REP_ID.list"

if [[ $EUID -ne 0 ]]; then
    echo "Run as root"
    exit 1
fi

command -v wget >/dev/null 2>&1 || {
    echo "Please install wget first."
    exit 1
}

# restart time server for time sync
systemctl restart systemd-timesyncd
timedatectl show-timesync --all

if ! command -v gpg >/dev/null 2>&1; then
    echo "gpg not found. Installing..."

    apt-get install -y gpg

    command -v gpg >/dev/null 2>&1 || {
        echo "Failed to install gpg." >&2
        exit 1
    }
fi

echo "Installing $REP_ID repository..."

install -d -m 755 /usr/share/keyrings

wget -qO "$KEYRING.asc" "$KEY_URL"
gpg --dearmor --yes -o "$KEYRING" "$KEYRING.asc"
rm -f "$KEYRING.asc"

cat >"$SOURCE_LIST" <<EOF
deb [signed-by=$KEYRING] $REPO_URL stable main
EOF

apt update

echo
echo "Repository $REP_ID installed."
