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

usage() {
  cat <<'EOF'
c-note self-hosting installer
Usage: install.sh [options]
  --install-dir DIR  Install/checkout directory
  --repo URL          Git repository URL
  --ref REF           Git branch/tag/commit (default: main)
  --help              Show this help
Defaults: /opt/c-note as root, $HOME/c-note otherwise; admin / c-note.
Existing .env and Docker data are preserved when rerun.
On Debian and Ubuntu, missing Git, curl, and Docker Engine/Compose are installed automatically.
EOF
}
log() { printf '[c-note] %s\n' "$*"; }
fail() { printf '[c-note] ERROR: %s\n' "$*" >&2; exit 1; }

DOCKER=(docker)

as_root() {
  if [[ "$EUID" == 0 ]]; then
    "$@"
  else
    command -v sudo >/dev/null 2>&1 || fail "sudo is required to install prerequisites; run this script as root or install sudo"
    sudo "$@"
  fi
}

install_prerequisites() {
  local need_docker=0
  if ! command -v docker >/dev/null 2>&1 || ! docker compose version >/dev/null 2>&1; then
    need_docker=1
  fi

  if command -v git >/dev/null 2>&1 && command -v curl >/dev/null 2>&1 && ((need_docker == 0)); then
    return
  fi

  [[ -r /etc/os-release ]] || fail "Cannot identify the operating system; install Git, curl, Docker Engine, and Docker Compose v2 manually"
  # shellcheck disable=SC1091
  . /etc/os-release
  local distro="${ID:-}"
  local supported=0
  [[ "$distro" == debian || "$distro" == ubuntu ]] && supported=1
  [[ " ${ID_LIKE:-} " == *" debian "* ]] && supported=1
  ((supported == 1)) || fail "Automatic prerequisite installation supports Debian and Ubuntu only; install Git, curl, Docker Engine, and Docker Compose v2 manually"
  command -v apt-get >/dev/null 2>&1 || fail "apt-get is required for automatic prerequisite installation"

  log "Installing required packages (Git, curl, and CA certificates)"
  as_root apt-get update
  as_root apt-get install -y ca-certificates curl git

  if ((need_docker == 1)); then
    log "Installing Docker Engine and Docker Compose v2"
    as_root apt-get install -y ca-certificates curl gnupg
    as_root install -d -m 0755 /etc/apt/keyrings
    if [[ ! -s /etc/apt/keyrings/docker.asc ]]; then
      curl --fail --silent --show-error https://download.docker.com/linux/"${distro}"/gpg | as_root tee /etc/apt/keyrings/docker.asc >/dev/null
      as_root chmod a+r /etc/apt/keyrings/docker.asc
    fi
    local codename="${VERSION_CODENAME:-${UBUNTU_CODENAME:-}}"
    [[ -n "$codename" ]] || fail "Could not determine the Debian/Ubuntu release codename for Docker"
    local arch
    arch="$(dpkg --print-architecture)"
    printf 'deb [arch=%s signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/%s %s stable\n' "$arch" "$distro" "$codename" | as_root tee /etc/apt/sources.list.d/docker.list >/dev/null
    as_root apt-get update
    as_root apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
    if command -v systemctl >/dev/null 2>&1; then
      as_root systemctl enable --now docker || true
    fi
  fi

  if docker info >/dev/null 2>&1; then
    DOCKER=(docker)
  else
    DOCKER=(sudo docker)
  fi
  "${DOCKER[@]}" compose version >/dev/null 2>&1 || fail "Docker Compose v2 is unavailable after installation"
}

INSTALL_DIR="${CNOTE_INSTALL_DIR:-}"
REPO_URL="${CNOTE_REPO_URL:-https://git.brunnerit.at/akadmin/c-note.git}"
REF="${CNOTE_REF:-main}"
while (($#)); do
  case "$1" in
    --install-dir) (($# >= 2)) || fail "--install-dir needs a directory"; INSTALL_DIR="$2"; shift 2 ;;
    --repo) (($# >= 2)) || fail "--repo needs a URL"; REPO_URL="$2"; shift 2 ;;
    --ref) (($# >= 2)) || fail "--ref needs a ref"; REF="$2"; shift 2 ;;
    --help|-h) usage; exit 0 ;;
    *) fail "unknown option: $1" ;;
  esac
done

if [[ -z "$INSTALL_DIR" ]]; then
  if [[ "$EUID" == 0 ]]; then INSTALL_DIR=/opt/c-note; else INSTALL_DIR="${HOME:-.}/c-note"; fi
fi
install_prerequisites

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
if [[ -f "$SCRIPT_DIR/server/compose.yaml" ]]; then
  SOURCE_DIR="$SCRIPT_DIR"
  log "Using checkout at $SOURCE_DIR"
else
  command -v git >/dev/null 2>&1 || fail "Git is required for a downloaded installer"
  if [[ -e "$INSTALL_DIR" ]]; then
    [[ -d "$INSTALL_DIR/.git" ]] || fail "$INSTALL_DIR exists but is not a Git checkout"
    SOURCE_DIR="$INSTALL_DIR"
    log "Updating checkout at $SOURCE_DIR"
    git -C "$SOURCE_DIR" fetch --depth 1 origin "$REF"
    git -C "$SOURCE_DIR" checkout --force "$REF"
    git -C "$SOURCE_DIR" reset --hard "origin/$REF" 2>/dev/null || true
  else
    mkdir -p "$(dirname -- "$INSTALL_DIR")"
    log "Downloading c-note from $REPO_URL"
    git clone --depth 1 --branch "$REF" "$REPO_URL" "$INSTALL_DIR"
    SOURCE_DIR="$INSTALL_DIR"
  fi
fi

SERVER_DIR="$SOURCE_DIR/server"
[[ -f "$SERVER_DIR/compose.yaml" ]] || fail "The checkout does not contain server/compose.yaml"
ENV_FILE="$SERVER_DIR/.env"
if [[ ! -e "$ENV_FILE" ]]; then
  cp "$SERVER_DIR/.env.example" "$ENV_FILE"
  # Make the first run usable immediately on a private LAN. Operators can
  # edit APP_ORIGIN and COOKIE_SECURE before a reverse-proxy deployment.
  sed -i.bak -e 's#^APP_ORIGIN=.*#APP_ORIGIN=http://localhost:3000#' -e 's#^COOKIE_SECURE=.*#COOKIE_SECURE=false#' "$ENV_FILE"
  rm -f "$ENV_FILE.bak"
  chmod 600 "$ENV_FILE"
  log "Created $ENV_FILE with localhost defaults"
else
  log "Keeping existing $ENV_FILE"
fi

log "Building and starting c-note"
"${DOCKER[@]}" compose --project-directory "$SERVER_DIR" --env-file "$ENV_FILE" -f "$SERVER_DIR/compose.yaml" up --build -d
log "Waiting for health endpoint"
ready=0
for _ in {1..30}; do
  if curl --silent --show-error --fail --max-time 3 http://127.0.0.1:3000/api/v1/health >/dev/null 2>&1; then ready=1; break; fi
  sleep 2
done
if ((ready != 1)); then
  "${DOCKER[@]}" compose --project-directory "$SERVER_DIR" --env-file "$ENV_FILE" -f "$SERVER_DIR/compose.yaml" ps
  fail "Server did not become healthy; inspect compose logs"
fi

log "c-note is running at http://localhost:3000"
printf 'Default login: admin / c-note\nChange the password immediately on first login.\n'
