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

REPO="watch-ly/agent"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# Ensure build dependencies are installed
echo "==> Checking build dependencies..."
for cmd in reprepro createrepo_c jq; do
    if ! command -v "$cmd" &>/dev/null; then
        echo "    Installing missing dependencies..."
        sudo apt-get update -qq
        sudo apt-get install -y -qq reprepro createrepo-c jq
        break
    fi
done

echo "==> Fetching latest release from ${REPO}..."
RELEASE_JSON=$(gh api "repos/${REPO}/releases/latest")
TAG=$(echo "$RELEASE_JSON" | jq -r '.tag_name')
echo "    Release: ${TAG}"

TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

# Download all .deb and .rpm assets
echo "==> Downloading packages..."
ASSET_NAMES=$(echo "$RELEASE_JSON" | jq -r '.assets[] | select(.name | test("\\.(deb|rpm)$")) | .name')
if [ -z "$ASSET_NAMES" ]; then
    echo "ERROR: No .deb or .rpm assets found in release ${TAG}" >&2
    exit 1
fi

for name in $ASSET_NAMES; do
    echo "    ${name}"
    gh release download "$TAG" --repo "$REPO" --pattern "$name" --dir "$TMPDIR"
done

# --- APT repo ---
echo "==> Building APT repository..."
mkdir -p apt
REPREPRO_BASE="${PWD}/apt"
export REPREPRO_BASE_DIR="${REPREPRO_BASE}"

# Set up reprepro config
mkdir -p "${REPREPRO_BASE}/conf"
cp "${SCRIPT_DIR}/conf/distributions" "${REPREPRO_BASE}/conf/distributions"

# Remove old packages so reprepro doesn't reject duplicates
reprepro --basedir "${REPREPRO_BASE}" removefilter stable 'Package (% *)' 2>/dev/null || true

for deb in "${TMPDIR}"/*.deb; do
    [ -f "$deb" ] || continue
    echo "    Adding $(basename "$deb")"
    reprepro --basedir "${REPREPRO_BASE}" includedeb stable "$deb"
done

# --- YUM repo ---
echo "==> Building YUM repository..."
mkdir -p rpm/x86_64 rpm/aarch64

for rpm_file in "${TMPDIR}"/*.rpm; do
    [ -f "$rpm_file" ] || continue
    filename=$(basename "$rpm_file")
    case "$filename" in
        *x86_64* | *amd64*)
            cp "$rpm_file" rpm/x86_64/
            echo "    x86_64: ${filename}"
            ;;
        *aarch64* | *arm64*)
            cp "$rpm_file" rpm/aarch64/
            echo "    aarch64: ${filename}"
            ;;
        *)
            echo "    WARN: Unknown arch for ${filename}, skipping"
            ;;
    esac
done

for arch_dir in rpm/x86_64 rpm/aarch64; do
    if ls "${arch_dir}"/*.rpm 1>/dev/null 2>&1; then
        echo "    createrepo_c ${arch_dir}"
        createrepo_c --update "${arch_dir}"
        gpg --batch --yes --detach-sign --armor "${arch_dir}/repodata/repomd.xml"
    fi
done

# --- GPG public key ---
echo "==> Exporting GPG public key..."
GPG_FINGERPRINT=$(gpg --list-keys --with-colons "Watchly" 2>/dev/null | awk -F: '/^fpr:/{print $10; exit}')
if [ -z "$GPG_FINGERPRINT" ]; then
    echo "ERROR: No GPG key found for 'Watchly'. Generate one first." >&2
    exit 1
fi
gpg --armor --export "${GPG_FINGERPRINT}" > gpg.key
echo "    Fingerprint: ${GPG_FINGERPRINT}"

# --- install.sh ---
echo "==> Generating install.sh..."
cat > install.sh << 'INSTALL_EOF'
#!/usr/bin/env bash
set -euo pipefail

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

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
    echo "deb [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 "watchly-agent installed successfully!"
echo "Run: sudo watchly-setup"
INSTALL_EOF

# Stamp the real fingerprint into install.sh
sed -i "s/__GPG_FINGERPRINT__/${GPG_FINGERPRINT}/g" install.sh
chmod +x install.sh

echo "==> Done. Webroot contents:"
echo "    apt/dists/stable/..."
echo "    apt/pool/main/..."
ls rpm/x86_64/*.rpm 2>/dev/null | sed 's/^/    /' || true
ls rpm/aarch64/*.rpm 2>/dev/null | sed 's/^/    /' || true
echo "    gpg.key"
echo "    install.sh"
