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

REPO_NAME="aqua"
PROVIDER_NAME="aetheros"
REPO_PATH="/etc/yum.repos.d/${PROVIDER_NAME}.repo"

REPO_URL="https://aetheros.kitechsoftware.com/conf/aqua/${PROVIDER_NAME}.repo"
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 Fedora"

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

  # Repo file
  curl -fsSL "$REPO_URL" | sudo tee "$REPO_PATH" >/dev/null

  # Import GPG key
  sudo rpm --import "$GPG_KEY_URL"

  sudo dnf makecache
  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 file
  if [[ -f "$REPO_PATH" ]]; then
    sudo rm -f "$REPO_PATH"
  fi

  # Remove GPG key (best-effort)
  rpm -q gpg-pubkey &>/dev/null || true
  KEY_IDS=$(rpm -q gpg-pubkey \
    | xargs rpm -qi \
    | awk '/AetherOS/{getline; print $NF}' || true)

  for key in $KEY_IDS; do
    sudo rpm -e "$key" || true
  done

  sudo dnf makecache
  echo_prefix "${REPO_NAME} repository removed"
}

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

  if [[ -f "$REPO_PATH" ]]; then
    echo "✓ Repo file exists"
  else
    echo "✗ Repo file missing"
  fi

  if rpm -q gpg-pubkey &>/dev/null && rpm -qi gpg-pubkey | grep -q "AetherOS"; then
    echo "✓ GPG key installed"
  else
    echo "✗ GPG key not installed"
  fi

  if sudo dnf repolist | grep -q "^${REPO_NAME}"; then
    echo "✓ Repo enabled"
  else
    echo "✗ Repo not enabled"
  fi
}

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

Commands:
  install        Add the AetherOS Fedora repository
  uninstall      Remove the repository and GPG trust
  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
