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

API_URL="${VOIDMAIL_BOOTSTRAP_API:-https://install.voidmail.email/api/bootstrap/}"
INSTALL_PATH="${VOIDMAIL_INSTALL_PATH:-/usr/local/bin/voidmail}"
RELEASE_CHANNEL="${VOIDMAIL_RELEASE_CHANNEL:-stable}"
TMP_DIR="$(mktemp -d /tmp/voidmail-bootstrap.XXXXXX)"
trap 'rm -rf "$TMP_DIR"' EXIT

if [[ -t 1 && "${TERM:-}" != "dumb" ]]; then
  C_RESET=$'\033[0m'
  C_TEXT=$'\033[38;5;255m'
  C_MUTED=$'\033[38;5;110m'
  C_ACCENT=$'\033[38;5;51m'
  C_VIOLET=$'\033[38;5;141m'
  C_SUCCESS=$'\033[38;5;84m'
  C_ERROR=$'\033[38;5;204m'
  C_BORDER=$'\033[38;5;67m'
else
  C_RESET=''
  C_TEXT=''
  C_MUTED=''
  C_ACCENT=''
  C_VIOLET=''
  C_SUCCESS=''
  C_ERROR=''
  C_BORDER=''
fi

print_header() {
  printf '\n'
  printf '%b%s%b\n' "$C_BORDER" '============================================================' "$C_RESET"
  printf '%b%s%b\n' "$C_ACCENT" '  VoidMail Bootstrap' "$C_RESET"
  printf '%b%s%b\n' "$C_MUTED" '  Secure CLI delivery for production VPS installs' "$C_RESET"
  printf '%b%s%b\n' "$C_BORDER" '============================================================' "$C_RESET"
  printf '\n'
}

step() {
  printf '%b->%b %b%s%b\n' "$C_ACCENT" "$C_RESET" "$C_TEXT" "$1" "$C_RESET"
}

ok() {
  printf '%bOK%b  %s\n' "$C_SUCCESS" "$C_RESET" "$1"
}

note() {
  printf '%b..%b  %s\n' "$C_MUTED" "$C_RESET" "$1"
}

info() {
  note "$1"
}

fail() {
  printf '\n%bERROR%b %s\n' "$C_ERROR" "$C_RESET" "$1" >&2
  exit 1
}

have_root() {
  [[ ${EUID:-$(id -u)} -eq 0 ]]
}

run_privileged() {
  if have_root; then
    "$@"
  elif command -v sudo >/dev/null 2>&1; then
    sudo "$@"
  else
    fail "Root privileges are required to install the CLI to ${INSTALL_PATH}."
  fi
}

install_binary() {
  local source_path="$1"
  local target_path="$2"
  local target_dir
  target_dir="$(dirname "$target_path")"

  if [[ -w "$target_dir" ]] || { [[ ! -e "$target_dir" ]] && [[ -w "$(dirname "$target_dir")" ]]; }; then
    mkdir -p "$target_dir"
    install -m 0755 "$source_path" "$target_path"
  else
    run_privileged mkdir -p "$target_dir"
    run_privileged install -m 0755 "$source_path" "$target_path"
  fi
}

ensure_package_manager() {
  if command -v apt-get >/dev/null 2>&1; then
    PKG_MANAGER="apt"
  elif command -v dnf >/dev/null 2>&1; then
    PKG_MANAGER="dnf"
  elif command -v yum >/dev/null 2>&1; then
    PKG_MANAGER="yum"
  else
    fail "Supported package manager not found. Expected apt, dnf, or yum."
  fi
}

install_missing_tools() {
  local missing=()
  for tool in curl jq bash install chmod mkdir; do
    command -v "$tool" >/dev/null 2>&1 || missing+=("$tool")
  done
  command -v sha256sum >/dev/null 2>&1 || command -v shasum >/dev/null 2>&1 || missing+=("checksum")

  if [[ ${#missing[@]} -eq 0 ]]; then
    return
  fi

  ensure_package_manager
  case "$PKG_MANAGER" in
    apt)
      run_privileged apt-get update -y >/dev/null 2>&1
      run_privileged apt-get install -y curl jq ca-certificates openssl coreutils >/dev/null 2>&1
      ;;
    dnf)
      run_privileged dnf install -y curl jq ca-certificates openssl coreutils >/dev/null 2>&1
      ;;
    yum)
      run_privileged yum install -y curl jq ca-certificates openssl coreutils >/dev/null 2>&1
      ;;
  esac
}

checksum_file() {
  local path="$1"
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$path" | awk '{print $1}'
  else
    shasum -a 256 "$path" | awk '{print $1}'
  fi
}

map_arch() {
  case "$(uname -m)" in
    x86_64|amd64) printf 'linux-amd64' ;;
    aarch64|arm64) printf 'linux-arm64' ;;
    *) fail "Unsupported CPU architecture: $(uname -m)" ;;
  esac
}

installed_version() {
  if [[ -x "$INSTALL_PATH" ]]; then
    "$INSTALL_PATH" version 2>/dev/null || true
  fi
}

parse_args() {
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --channel)
        RELEASE_CHANNEL="${2:-}"
        shift 2
        ;;
      --channel=*)
        RELEASE_CHANNEL="${1#*=}"
        shift
        ;;
      *)
        fail "Unknown argument: $1"
        ;;
    esac
  done
}

normalize_channel() {
  case "${1,,}" in
    stable|dev) printf '%s' "${1,,}" ;;
    *) fail "Unsupported release channel: $1 (expected stable or dev)" ;;
  esac
}

main() {
  parse_args "$@"
  RELEASE_CHANNEL="$(normalize_channel "$RELEASE_CHANNEL")"
  print_header
  [[ "$(uname -s)" == "Linux" ]] || fail "VoidMail v1 supports Ubuntu Linux only."
  step "Checking local bootstrap requirements"
  install_missing_tools
  ok "Bootstrap dependencies are ready"

  local arch response version download_url sha256 filename binary_path current_version
  arch="$(map_arch)"
  step "Resolving the latest signed VoidMail CLI for ${arch} on ${RELEASE_CHANNEL}"
  response="$(curl -fsSL "${API_URL}?arch=${arch}&channel=${RELEASE_CHANNEL}")" || fail "Unable to fetch bootstrap metadata."
  version="$(echo "$response" | jq -r '.version // empty')"
  download_url="$(echo "$response" | jq -r '.download_url // empty')"
  sha256="$(echo "$response" | jq -r '.sha256 // empty')"
  filename="$(echo "$response" | jq -r '.filename // "voidmail"')"
  [[ -n "$version" ]] || fail "Bootstrap metadata did not include a CLI version."
  [[ -n "$download_url" ]] || fail "Bootstrap metadata did not include a download URL."
  [[ -n "$sha256" ]] || fail "Bootstrap metadata did not include a checksum."

  current_version="$(installed_version)"
  if [[ -n "$current_version" && "$current_version" == "$version" ]]; then
    ok "VoidMail CLI v${version} is already installed"
    printf '\n%bNext%b\n' "$C_VIOLET" "$C_RESET"
    printf '  Run %bvoidmail%b to open the installer or lifecycle console.\n\n' "$C_TEXT" "$C_RESET"
    exit 0
  fi

  binary_path="$TMP_DIR/$filename"
  step "Downloading VoidMail CLI v${version}"
  curl -fsSL "$download_url" -o "$binary_path" || fail "Failed to download the VoidMail CLI."
  ok "Signed CLI package downloaded"
  step "Verifying release checksum"
  [[ "$(checksum_file "$binary_path")" == "$sha256" ]] || fail "Checksum validation failed for the CLI binary."
  chmod +x "$binary_path"
  ok "Checksum verified"

  step "Installing VoidMail CLI to ${INSTALL_PATH}"
  install_binary "$binary_path" "$INSTALL_PATH"
  ok "VoidMail CLI v${version} is ready"

  printf '\n%bBootstrap complete%b\n' "$C_ACCENT" "$C_RESET"
  printf '  CLI version : %b%s%b\n' "$C_TEXT" "$version" "$C_RESET"
  printf '  Channel     : %b%s%b\n' "$C_TEXT" "$RELEASE_CHANNEL" "$C_RESET"
  printf '  Install path: %b%s%b\n' "$C_TEXT" "$INSTALL_PATH" "$C_RESET"
  printf '\n%bNext%b\n' "$C_VIOLET" "$C_RESET"
  printf '  Run %bvoidmail%b to start the guided production install.\n\n' "$C_TEXT" "$C_RESET"
}

main "$@"
