#!/usr/bin/env bash
set -euo pipefail

REPO_URL="https://repo.watch.ly"
GPG_KEY_URL="${REPO_URL}/gpg.key"
GPG_FINGERPRINT="14216134F66F03D9B721185C1F490F8AA18AA936"

if [ "$(id -u)" -ne 0 ]; then
    echo "Error: this script must be run as root (or via sudo)." >&2
    exit 1
fi

install_apt() {
    echo "==> Detected Debian/Ubuntu — configuring APT repository..."
    apt-get update -qq
    apt-get install -y -qq curl gnupg >/dev/null

    curl -fsSL "$GPG_KEY_URL" | gpg --dearmor -o /usr/share/keyrings/watchly-archive-keyring.gpg
    # arch=amd64,arm64 stops apt from trying to fetch i386 (or other foreign
    # arches enabled on the host) indexes from this repo, which only ships those two.
    echo "deb [arch=amd64,arm64 signed-by=/usr/share/keyrings/watchly-archive-keyring.gpg] ${REPO_URL}/apt stable main" \
        > /etc/apt/sources.list.d/watchly.list

    apt-get update -qq
    apt-get install -y watchly-agent
}

install_yum() {
    echo "==> Detected RHEL/CentOS/Fedora — configuring YUM repository..."
    rpm --import "$GPG_KEY_URL"

    ARCH=$(uname -m)
    cat > /etc/yum.repos.d/watchly.repo << YUMEOF
[watchly]
name=Watchly Agent Repository
baseurl=${REPO_URL}/rpm/${ARCH}/
enabled=1
gpgcheck=1
gpgkey=${GPG_KEY_URL}
YUMEOF

    if command -v dnf &>/dev/null; then
        dnf install -y watchly-agent
    else
        yum install -y watchly-agent
    fi
}

if [ -f /etc/debian_version ]; then
    install_apt
elif [ -f /etc/redhat-release ] || [ -f /etc/fedora-release ]; then
    install_yum
else
    echo "Error: unsupported distribution. Install manually from ${REPO_URL}" >&2
    exit 1
fi

echo ""
echo "=== Watch.ly Automated Setup ==="
echo "Run: sudo watchly-setup"
