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

# Synora production bootstrap installer
# Official endpoint: https://synora.codesec.me/install.sh
# Usage:
#   curl -fsSL https://synora.codesec.me/install.sh | sudo bash
#   curl -fsSL https://synora.codesec.me/install.sh | sudo bash -s -- --version 0.3.1

readonly SYNORA_REPO_OWNER="altafpasha"
readonly SYNORA_REPO_NAME="synora"
readonly SYNORA_REPO_URL="https://github.com/${SYNORA_REPO_OWNER}/${SYNORA_REPO_NAME}"
readonly DEFAULT_SYNORA_VERSION="0.3.1"
readonly DEFAULT_INSTALL_DIR="/opt/synora"

SYNORA_VERSION="${SYNORA_VERSION:-$DEFAULT_SYNORA_VERSION}"
INSTALL_DIR="${SYNORA_INSTALL_DIR:-$DEFAULT_INSTALL_DIR}"
EXPECTED_SHA256="${SYNORA_SHA256:-}"
DOWNLOAD_METHOD="${SYNORA_DOWNLOAD_METHOD:-auto}"
ALLOW_UNSUPPORTED_OS="${SYNORA_ALLOW_UNSUPPORTED_OS:-0}"
CONFIRM_EXISTING="${SYNORA_CONFIRM_EXISTING:-0}"
DRY_RUN="${SYNORA_DRY_RUN:-0}"
SKIP_EXEC="${SYNORA_SKIP_EXEC:-0}"

TMP_DIR=""

cleanup() {
  local exit_code=$?
  if [[ -n "${TMP_DIR:-}" && -d "$TMP_DIR" ]]; then
    rm -rf -- "$TMP_DIR"
  fi
  exit "$exit_code"
}

trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM

log_info() {
  printf '[synora] %s\n' "$*"
}

log_warn() {
  printf '[synora] WARNING: %s\n' "$*" >&2
}

log_error() {
  printf '[synora] ERROR: %s\n' "$*" >&2
}

usage() {
  cat <<EOF
Synora Bootstrap Installer (v${DEFAULT_SYNORA_VERSION})

Usage:
  curl -fsSL https://synora.codesec.me/install.sh | sudo bash
  curl -fsSL https://synora.codesec.me/install.sh | sudo bash -s -- [options]

Options:
  -v, --version <tag>       Release tag to install (default: ${DEFAULT_SYNORA_VERSION})
  -d, --dir <path>          Installation directory (default: ${DEFAULT_INSTALL_DIR})
      --sha256 <hex>        Verify downloaded archive against an expected SHA-256 checksum
      --git                 Clone repository via Git instead of downloading release tarball
      --confirm-existing    Update an existing installation in place without prompting
      --allow-unsupported-os
                            Bypass Ubuntu 22.04/24.04 OS version enforcement
      --dry-run             Run preflight checks without downloading or modifying files
  -h, --help                Show this help message

Environment variables:
  SYNORA_VERSION            Same as --version
  SYNORA_INSTALL_DIR        Same as --dir
  SYNORA_SHA256             Same as --sha256
EOF
}

parse_args() {
  while [[ $# -gt 0 ]]; do
    case "$1" in
      -v|--version)
        if [[ -z "${2:-}" ]]; then
          log_error "--version requires a tag or ref argument."
          exit 1
        fi
        SYNORA_VERSION="$2"
        shift 2
        ;;
      -d|--dir)
        if [[ -z "${2:-}" ]]; then
          log_error "--dir requires a directory path."
          exit 1
        fi
        INSTALL_DIR="$2"
        shift 2
        ;;
      --sha256)
        if [[ -z "${2:-}" ]]; then
          log_error "--sha256 requires a 64-character hex digest."
          exit 1
        fi
        EXPECTED_SHA256="$2"
        shift 2
        ;;
      --git)
        DOWNLOAD_METHOD="git"
        shift
        ;;
      --confirm-existing)
        CONFIRM_EXISTING="1"
        shift
        ;;
      --allow-unsupported-os)
        ALLOW_UNSUPPORTED_OS="1"
        shift
        ;;
      --dry-run)
        DRY_RUN="1"
        shift
        ;;
      -h|--help)
        usage
        exit 0
        ;;
      *)
        log_error "Unknown option: $1"
        usage >&2
        exit 1
        ;;
    esac
  done
}

validate_inputs() {
  if [[ ! "$SYNORA_VERSION" =~ ^[A-Za-z0-9._-]+$ ]]; then
    log_error "Invalid version identifier '${SYNORA_VERSION}'."
    exit 1
  fi

  if [[ "$SYNORA_VERSION" == "main" || "$SYNORA_VERSION" == "master" ]]; then
    log_warn "Using mutable branch '${SYNORA_VERSION}' instead of a pinned release tag (default: ${DEFAULT_SYNORA_VERSION})."
    if [[ "$DOWNLOAD_METHOD" == "auto" ]]; then
      DOWNLOAD_METHOD="git"
    fi
  fi

  if [[ -n "$EXPECTED_SHA256" ]] && [[ ! "$EXPECTED_SHA256" =~ ^[A-Fa-f0-9]{64}$ ]]; then
    log_error "Invalid --sha256 digest format. Expected 64 hexadecimal characters."
    exit 1
  fi

  if [[ -z "$INSTALL_DIR" || "$INSTALL_DIR" == "/" ]]; then
    log_error "Invalid installation directory '${INSTALL_DIR}'."
    exit 1
  fi
}

check_root() {
  if [[ "${EUID}" -ne 0 ]] && [[ "${SYNORA_ALLOW_NON_ROOT:-0}" != "1" ]]; then
    log_error "Root privileges are required to install Synora."
    printf 'Run with sudo:\n  curl -fsSL https://synora.codesec.me/install.sh | sudo bash\n' >&2
    exit 1
  fi
}

detect_os() {
  local os_file="${SYNORA_OS_RELEASE_FILE:-/etc/os-release}"
  OS_ID="unknown"
  OS_VERSION="unknown"
  OS_PRETTY="Unknown OS"

  if [[ -r "$os_file" ]]; then
    OS_ID="$(awk -F= '/^ID=/{gsub(/"/,"",$2); print $2; exit}' "$os_file")"
    OS_VERSION="$(awk -F= '/^VERSION_ID=/{gsub(/"/,"",$2); print $2; exit}' "$os_file")"
    OS_PRETTY="$(awk -F= '/^PRETTY_NAME=/{gsub(/"/,"",$2); print $2; exit}' "$os_file")"
  fi

  if [[ "$OS_ID" != "ubuntu" ]] || [[ "$OS_VERSION" != "22.04" && "$OS_VERSION" != "24.04" ]]; then
    if [[ "$ALLOW_UNSUPPORTED_OS" == "1" ]]; then
      log_warn "Bypassing OS check for '${OS_PRETTY}' (ID=${OS_ID}, VERSION_ID=${OS_VERSION})."
    else
      log_error "Unsupported operating system: '${OS_PRETTY}' (ID=${OS_ID}, VERSION_ID=${OS_VERSION})."
      log_error "Synora officially supports Ubuntu 22.04 LTS and Ubuntu 24.04 LTS."
      log_error "To override at your own risk, set SYNORA_ALLOW_UNSUPPORTED_OS=1 or pass --allow-unsupported-os."
      exit 1
    fi
  fi
}

detect_architecture() {
  local raw_arch="${SYNORA_ARCH:-$(uname -m)}"
  case "$raw_arch" in
    x86_64|amd64)
      TARGET_ARCH="AMD64"
      ;;
    aarch64|arm64)
      TARGET_ARCH="ARM64"
      ;;
    *)
      log_error "Unsupported CPU architecture '${raw_arch}'. Synora supports AMD64 (x86_64) and ARM64 (aarch64)."
      exit 1
      ;;
  esac
}

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

check_dependencies() {
  local missing_cmds=()
  local apt_pkgs=()

  local cmd
  for cmd in curl git tar openssl; do
    if ! command -v "$cmd" >/dev/null 2>&1; then
      missing_cmds+=("$cmd")
      apt_pkgs+=("$cmd")
    fi
  done

  if ! command -v sha256sum >/dev/null 2>&1 && ! command -v shasum >/dev/null 2>&1; then
    missing_cmds+=("sha256sum")
    apt_pkgs+=("coreutils")
  fi

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

  if [[ "$DRY_RUN" == "1" ]] || [[ "${SYNORA_NO_APT:-0}" == "1" ]] || ! command -v apt-get >/dev/null 2>&1 || [[ "${EUID}" -ne 0 ]]; then
    log_error "Missing required dependencies: ${missing_cmds[*]}"
    log_error "Install them on Ubuntu with: sudo apt-get update && sudo apt-get install -y git curl tar openssl ca-certificates"
    exit 1
  fi

  log_info "Installing missing prerequisite packages: ${apt_pkgs[*]} ca-certificates"
  apt-get update
  apt-get install -y --no-install-recommends "${apt_pkgs[@]}" ca-certificates
}

prompt_yes_no() {
  local question="$1"
  local reply=""

  if [[ "${SYNORA_NON_INTERACTIVE:-0}" == "1" ]]; then
    return 1
  fi

  if [[ -t 0 ]]; then
    read -r -p "$question" reply || return 1
  elif [[ -e /dev/tty ]] && (: </dev/tty) 2>/dev/null; then
    read -r -p "$question" reply </dev/tty || return 1
  else
    return 1
  fi

  [[ "$reply" =~ ^[Yy]$ ]]
}

inspect_existing_installation() {
  EXISTING_STATE="none"
  if [[ ! -e "$INSTALL_DIR" ]]; then
    return 0
  fi

  if [[ ! -d "$INSTALL_DIR" ]]; then
    log_error "Target path '${INSTALL_DIR}' exists and is not a directory."
    exit 1
  fi

  if [[ -z "$(ls -A "$INSTALL_DIR" 2>/dev/null)" ]]; then
    return 0
  fi

  if [[ -f "$INSTALL_DIR/deployment/standard/.env" ]] || [[ -d "$INSTALL_DIR/deployment/standard/data/couchdb" && -n "$(ls -A "$INSTALL_DIR/deployment/standard/data/couchdb" 2>/dev/null)" ]]; then
    EXISTING_STATE="Standard Mode deployment"
  elif [[ -f "$INSTALL_DIR/deployment/lite/.env" ]] || [[ -f "$INSTALL_DIR/deployment/lite/data/api/synora.db" ]]; then
    EXISTING_STATE="Lite Mode deployment"
  elif [[ -f "$INSTALL_DIR/deployment/.env" ]] || [[ -d "$INSTALL_DIR/deployment/data/couchdb" && -n "$(ls -A "$INSTALL_DIR/deployment/data/couchdb" 2>/dev/null)" ]]; then
    EXISTING_STATE="Legacy deployment"
  elif [[ -f "$INSTALL_DIR/installer/install.sh" ]]; then
    EXISTING_STATE="Existing Synora directory"
  else
    EXISTING_STATE="Non-empty directory"
  fi

  if [[ "$CONFIRM_EXISTING" == "1" ]]; then
    log_info "Confirmed in-place update for existing installation at '${INSTALL_DIR}' (${EXISTING_STATE})."
    return 0
  fi

  log_warn "Existing installation detected at '${INSTALL_DIR}' (${EXISTING_STATE})."
  if [[ "$DRY_RUN" == "1" ]]; then
    log_error "Refusing to overwrite existing installation in dry-run without --confirm-existing."
    exit 1
  fi

  if ! prompt_yes_no "Update repository files in '${INSTALL_DIR}' (preserving data/ and .env) and continue? [y/N]: "; then
    log_error "Aborted without modifying existing installation at '${INSTALL_DIR}'."
    exit 1
  fi
}

verify_checksum_if_available() {
  local archive_path="$1"
  local checksums_file="$2"
  local archive_name
  archive_name="$(basename "$archive_path")"

  local actual_sha256
  if ! actual_sha256="$(compute_sha256 "$archive_path")"; then
    log_error "Unable to compute SHA-256 checksum (missing sha256sum/shasum)."
    exit 1
  fi

  if [[ -n "$EXPECTED_SHA256" ]]; then
    local expected_lower
    expected_lower="$(printf '%s' "$EXPECTED_SHA256" | tr '[:upper:]' '[:lower:]')"
    if [[ "$actual_sha256" != "$expected_lower" ]]; then
      log_error "SHA-256 verification failed for ${archive_name}."
      log_error "  Expected: ${expected_lower}"
      log_error "  Actual:   ${actual_sha256}"
      exit 1
    fi
    log_info "Verified archive SHA-256 against provided checksum (${actual_sha256})."
    return 0
  fi

  if [[ -s "$checksums_file" ]]; then
    local published_sha256
    published_sha256="$(awk -v target="$archive_name" '
      NF >= 2 {
        file = $2
        sub(/^\*/, "", file)
        sub(/^\.\//, "", file)
        if (file == target) {
          print tolower($1)
          exit
        }
      }
    ' "$checksums_file")"

    if [[ -n "$published_sha256" ]]; then
      if [[ "$actual_sha256" != "$published_sha256" ]]; then
        log_error "Published checksum verification failed for ${archive_name}."
        log_error "  Expected: ${published_sha256}"
        log_error "  Actual:   ${actual_sha256}"
        exit 1
      fi
      log_info "Verified archive SHA-256 against published SHA256SUMS (${actual_sha256})."
      return 0
    fi
  fi

  log_warn "No published SHA256SUMS asset found for ${SYNORA_VERSION}; continuing with verified HTTPS tarball structure check."
}

validate_extracted_tree() {
  local src_dir="$1"
  local required_files=(
    "installer/install.sh"
    "installer/lib/system-detect.sh"
    "installer/pair.sh"
    "installer/upgrade-to-standard.sh"
    "installer/backup-and-restore.sh"
    "deployment/lite/docker-compose.yml"
    "deployment/standard/docker-compose.yml"
    "server/Dockerfile"
    "server/package.json"
  )

  local rel_path
  for rel_path in "${required_files[@]}"; do
    if [[ ! -f "$src_dir/$rel_path" ]]; then
      log_error "Downloaded archive is incomplete: missing '${rel_path}'."
      exit 1
    fi
  done
}

download_and_stage() {
  TMP_DIR="$(mktemp -d -t synora-bootstrap.XXXXXX)"
  local src_dir="$TMP_DIR/src"
  mkdir -p "$src_dir"

  if [[ "$DOWNLOAD_METHOD" == "git" ]]; then
    log_info "Cloning Synora (${SYNORA_VERSION}) from ${SYNORA_REPO_URL}..."
    if ! git clone --depth 1 --branch "$SYNORA_VERSION" "${SYNORA_REPO_URL}.git" "$src_dir"; then
      log_error "Failed to clone Synora ref '${SYNORA_VERSION}' from ${SYNORA_REPO_URL}.git."
      exit 1
    fi
    validate_extracted_tree "$src_dir"
    return 0
  fi

  local checksums_url="${SYNORA_CHECKSUMS_URL:-${SYNORA_REPO_URL}/releases/download/${SYNORA_VERSION}/SHA256SUMS}"
  local checksums_file="$TMP_DIR/SHA256SUMS"
  local release_tar_name="synora-${SYNORA_VERSION}.tar.gz"
  local release_tar_url="${SYNORA_REPO_URL}/releases/download/${SYNORA_VERSION}/${release_tar_name}"
  local tag_tar_url="${SYNORA_ARCHIVE_URL:-${SYNORA_REPO_URL}/archive/refs/tags/${SYNORA_VERSION}.tar.gz}"
  local archive_path=""

  if curl -fsSL --proto '=https' --tlsv1.2 "$checksums_url" -o "$checksums_file" 2>/dev/null; then
    if grep -qE "[[:space:]][*./]*${release_tar_name}\$" "$checksums_file"; then
      archive_path="$TMP_DIR/${release_tar_name}"
      log_info "Downloading release archive ${release_tar_name}..."
      if ! curl -fsSL --proto '=https' --tlsv1.2 "$release_tar_url" -o "$archive_path"; then
        log_error "Failed to download release archive from ${release_tar_url}."
        exit 1
      fi
    fi
  else
    rm -f "$checksums_file"
  fi

  if [[ -z "$archive_path" ]]; then
    archive_path="$TMP_DIR/${SYNORA_VERSION}.tar.gz"
    log_info "Downloading Synora release tag ${SYNORA_VERSION}..."
    if ! curl -fsSL --proto '=https' --tlsv1.2 "$tag_tar_url" -o "$archive_path"; then
      log_error "Failed to download Synora release '${SYNORA_VERSION}' from ${tag_tar_url}."
      log_error "Check that tag '${SYNORA_VERSION}' exists at ${SYNORA_REPO_URL}/releases."
      exit 1
    fi
  fi

  verify_checksum_if_available "$archive_path" "$checksums_file"

  if ! tar -tzf "$archive_path" >/dev/null 2>&1; then
    log_error "Downloaded file is not a valid gzip tar archive."
    exit 1
  fi

  tar -xzf "$archive_path" -C "$src_dir" --strip-components=1
  validate_extracted_tree "$src_dir"
}

sync_staged_to_install_dir() {
  local src_dir="$TMP_DIR/src"
  mkdir -p "$INSTALL_DIR"

  if [[ "$EXISTING_STATE" == "none" ]]; then
    cp -a "$src_dir/." "$INSTALL_DIR/"
  else
    log_info "Updating repository files in '${INSTALL_DIR}' while preserving existing deployment data and .env files..."
    tar -C "$src_dir" \
      --exclude='deployment/lite/.env' \
      --exclude='deployment/lite/data' \
      --exclude='deployment/standard/.env' \
      --exclude='deployment/standard/data' \
      --exclude='deployment/standard/config' \
      --exclude='deployment/.env' \
      --exclude='deployment/data' \
      --exclude='deployment/backups' \
      -cf - . | tar -C "$INSTALL_DIR" -xf -
  fi

  chmod +x \
    "$INSTALL_DIR/installer/install.sh" \
    "$INSTALL_DIR/installer/pair.sh" \
    "$INSTALL_DIR/installer/upgrade-to-standard.sh" \
    "$INSTALL_DIR/installer/backup-and-restore.sh" \
    "$INSTALL_DIR/installer/lib/system-detect.sh"
}

run_installer() {
  if [[ "$SKIP_EXEC" == "1" ]]; then
    log_info "SYNORA_SKIP_EXEC=1 set; staged Synora ${SYNORA_VERSION} at '${INSTALL_DIR}' without executing installer/install.sh."
    return 0
  fi

  log_info "Launching Synora installer (${INSTALL_DIR}/installer/install.sh)..."
  if [[ ! -t 0 ]] && [[ -e /dev/tty ]] && (: </dev/tty) 2>/dev/null; then
    bash "$INSTALL_DIR/installer/install.sh" </dev/tty
  else
    bash "$INSTALL_DIR/installer/install.sh"
  fi
}

main() {
  parse_args "$@"
  validate_inputs
  check_root
  detect_os
  detect_architecture
  check_dependencies
  inspect_existing_installation

  log_info "System verified: ${OS_PRETTY} (${TARGET_ARCH}), version=${SYNORA_VERSION}, target=${INSTALL_DIR}"

  if [[ "$DRY_RUN" == "1" ]]; then
    log_info "Dry run complete. No files were downloaded or modified."
    exit 0
  fi

  download_and_stage
  sync_staged_to_install_dir
  run_installer
}

main "$@"
