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

REPO_NAME="terra"
PROVIDER_NAME="aetheros"
SOURCES_PATH="/etc/apt/sources.list.d/${REPO_NAME}.sources"
KEYRING_PATH="/usr/share/keyrings/${PROVIDER_NAME}.gpg"

SOURCES_URL="https://aetheros.kitechsoftware.com/conf/terra/${PROVIDER_NAME}.sources"
GPG_KEY_URL="https://aetheros.kitechsoftware.com/repo/gpg/${PROVIDER_NAME}.pub"

AUTO_YES=0
COMMAND=""

echo_prefix() {
  echo "==> $*"
}

confirm() {
  [[ "$AUTO_YES" -eq 1 ]] && return 0
  read -rp "$1 [y/N] " reply
  [[ "$reply" == "y" || "$reply" == "Y" ]]
}

install() {
  echo_prefix "Adding AetherOS (${REPO_NAME}) repository for Debian"

  if ! confirm "Proceed with installation?"; then
    echo "Aborted."
    exit 1
  fi

  # Repo sources
  curl -fsSL "$SOURCES_URL" | sudo tee "$SOURCES_PATH" >/dev/null

  # Install scoped GPG key (no apt-key)
  curl -fsSL "$GPG_KEY_URL" \
    | gpg --dearmor \
    | sudo tee "$KEYRING_PATH" >/dev/null

  sudo apt update
  echo_prefix "${REPO_NAME} repository added"
}

uninstall() {
  echo_prefix "Removing AetherOS (${REPO_NAME}) repository"

  if ! confirm "Remove ${REPO_NAME} repository and trust?"; then
    echo "Aborted."
    exit 1
  fi

  # Remove repo list
  if [[ -f "$SOURCES_PATH" ]]; then
    sudo rm -f "$SOURCES_PATH" "$KEYRING_PATH"
  fi

  # Remove keyring
  if [[ -f "$KEYRING_PATH" ]]; then
    sudo rm -f "$KEYRING_PATH"
  fi

  sudo apt update
  echo_prefix "${REPO_NAME} repository removed"
}

check() {
  echo_prefix "Checking AetherOS (${REPO_NAME}) repository"

  if [[ -f "$SOURCES_PATH" ]]; then
    echo "✓ Sources list exists"
  else
    echo "✗ Sources list missing"
  fi

  if [[ -f "$KEYRING_PATH" ]]; then
    echo "✓ GPG keyring installed"
  else
    echo "✗ GPG keyring missing"
  fi

  if grep -q "aetheros" "$LIST_PATH" 2>/dev/null; then
    echo "✓ Repo appears configured"
  else
    echo "✗ Repo not detected in sources list"
  fi
}

usage() {
  cat <<EOF
Usage: $0 <command> [options]

Commands:
  install        Add the AetherOS (${REPO_NAME}) Debian repository
  uninstall      Remove the repository and GPG key
  remove         Alias for uninstall
  check          Verify repository configuration
  help           Show this message

Options:
  -y, --yes      Skip confirmation prompts
  -h, --help     Show help
EOF
}

# Argument parsing
while [[ $# -gt 0 ]]; do
  case "$1" in
    install|uninstall|remove|check)
      COMMAND="$1"
      shift
      ;;
    -y|--yes)
      AUTO_YES=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown option: $1"
      usage
      exit 1
      ;;
  esac
done

case "$COMMAND" in
  install)
    install
    ;;
  uninstall|remove)
    uninstall
    ;;
  check)
    check
    ;;
  ""|help)
    usage
    ;;
  *)
    echo "Unknown command: $COMMAND"
    usage
    exit 1
    ;;
esac
