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

########################################
# CONFIG
########################################

REPO_URL="https://pkg.elysiacloud.com"
KEY_URL="https://pkg.elysiacloud.com/pkg.asc"

KEYRING_PATH="/usr/share/keyrings/elysiacloud-archive-keyring.gpg"
SOURCE_LIST="/etc/apt/sources.list.d/elysiacloud.list"

SUPPORTED_DISTROS=("jammy" "noble")

LOG="[ELYSIACLOUD-REPO]"

########################################
# FUNCTIONS
########################################

log() {
  echo "$LOG $1"
}

die() {
  echo "$LOG ERROR: $1" >&2
  exit 1
}

########################################
# REQUIREMENTS
########################################

if [[ $EUID -ne 0 ]]; then
  die "Please run as root (use sudo)"
fi

command -v curl >/dev/null || die "curl is required"
command -v gpg >/dev/null || die "gpg is required"

########################################
# DETECT DISTRO
########################################

if [[ -r /etc/os-release ]]; then
  . /etc/os-release
else
  die "Cannot detect OS"
fi

if [[ "${ID:-}" != "ubuntu" ]]; then
  die "Unsupported OS: ${ID:-unknown} (Ubuntu only)"
fi

CODENAME="${VERSION_CODENAME:-}"

if [[ -z "$CODENAME" ]]; then
  die "Could not determine Ubuntu codename"
fi

SUPPORTED=false
for d in "${SUPPORTED_DISTROS[@]}"; do
  if [[ "$CODENAME" == "$d" ]]; then
    SUPPORTED=true
    break
  fi
done

$SUPPORTED || die "Unsupported Ubuntu version: $CODENAME"

log "Detected Ubuntu $VERSION ($CODENAME)"

########################################
# INSTALL KEY
########################################

log "Installing repository signing key"

curl -fsSL "$KEY_URL" \
  | gpg --dearmor \
  | tee "$KEYRING_PATH" >/dev/null

chmod 644 "$KEYRING_PATH"

########################################
# ADD APT SOURCE
########################################

log "Adding APT source"

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

chmod 644 "$SOURCE_LIST"

########################################
# UPDATE
########################################

log "Updating package index"

apt update

log "Repository installed successfully"
log "You can now install packages from Elysia Cloud"

