#!/usr/bin/env bash
# NetWatcher installer: first install, or repair/upgrade of an existing one (.env is kept).
#
#   From an extracted package:   ./netwatcher/install.sh [options]
#   Standalone (downloads it):   curl -fsSLO <forge>/api/packages/danielvalat/generic/netwatcher/<version>/install.sh
#                                bash install.sh [options]
#
# Options:
#   --root DIR          install root (default /var/www/netwatcher)
#   --version X.Y.Z     download this version from the Gitea package registry
#   --package FILE|URL  install this zip instead of the latest release
#   --yes               no questions: take defaults and NW_* variables (see configure_env)
#   -h, --help
#
# Layout (same as deploy.sh and the in-app updater):
#   <root>/.env                    settings and secrets (written once, never overwritten)
#   <root>/ecosystem.config.cjs    pm2 process file
#   <root>/apprun/                 running build      <root>/apprun.prev/  previous build
#   <root>/releases/<version>/     extracted package  <root>/logs/         pm2 logs
#
# Needs: Linux, Node.js >= 22, a MySQL 8 / MariaDB database, curl and unzip (standalone only).
# Run it as the user that runs the app (not root): pm2 and the in-app updater use that user.
set -Eeuo pipefail

FEED_URL="${NW_FEED_URL:-https://services.teslina.net/api/v2/marketplace-repositories/teslina-netwatcher}"
PACKAGE_BASE="${NW_PACKAGE_BASE:-https://forge.teslina.net/api/packages/danielvalat/generic/netwatcher}"
APP_NAME="netwatcher"

ROOT="/var/www/netwatcher"
VERSION=""
PACKAGE=""
YES=0

log()  { printf '\033[1;34m==>\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m!!\033[0m %s\n' "$*" >&2; }
die()  { printf '\033[1;31mxx\033[0m %s\n' "$*" >&2; exit 1; }

usage() { sed -n '2,25p' "$0" | sed 's/^# \{0,1\}//'; exit 0; }

# Prompts read the terminal, so `curl … | bash` works too. With --yes, the default is taken.
ask() {
    local prompt="$1" default="${2:-}" answer=""
    if [[ $YES -eq 1 || ! -r /dev/tty ]]; then
        printf '%s' "$default"
        return
    fi
    if [[ -n "$default" ]]; then read -r -p "$prompt [$default]: " answer </dev/tty
    else read -r -p "$prompt: " answer </dev/tty; fi
    printf '%s' "${answer:-$default}"
}
ask_secret() {
    local prompt="$1" default="${2:-}" answer=""
    if [[ $YES -eq 1 || ! -r /dev/tty ]]; then
        printf '%s' "$default"
        return
    fi
    read -r -s -p "$prompt${default:+ [keep current]}: " answer </dev/tty
    echo >/dev/tty
    printf '%s' "${answer:-$default}"
}
confirm() {
    [[ $YES -eq 1 ]] && return 0
    local answer
    answer="$(ask "$1 (y/n)" "${2:-y}")"
    [[ "$answer" =~ ^[Yy] ]]
}

parse_args() {
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --root) ROOT="${2:?--root needs a directory}"; shift 2 ;;
            --version) VERSION="${2:?--version needs a version}"; VERSION="${VERSION#v}"; shift 2 ;;
            --package) PACKAGE="${2:?--package needs a file or URL}"; shift 2 ;;
            --yes|-y) YES=1; shift ;;
            -h|--help) usage ;;
            *) die "unknown option: $1 (see --help)" ;;
        esac
    done
    ROOT="${ROOT%/}"
}

check_prerequisites() {
    [[ "$(uname -s)" == "Linux" ]] || die "NetWatcher installs on Linux only"
    [[ $EUID -ne 0 ]] || warn "Running as root: pm2 and the app will run as root. A dedicated user is safer."
    command -v node >/dev/null || die "Node.js is not installed (version 22 or later is needed): https://nodejs.org/en/download"
    local major
    major="$(node -p 'process.versions.node.split(".")[0]')"
    [[ "$major" -ge 22 ]] || die "Node.js $(node -v) is too old: version 22 or later is needed"
    command -v npm >/dev/null || die "npm is not installed"

    if ! command -v pm2 >/dev/null; then
        confirm "pm2 (process manager) is not installed. Install it now with npm install -g pm2?" || die "pm2 is needed"
        if [[ -w "$(npm prefix -g)/lib" || $EUID -eq 0 ]]; then npm install -g pm2
        else sudo npm install -g pm2; fi
        command -v pm2 >/dev/null || die "pm2 is still not on PATH"
    fi
}

# Sets SRC to the netwatcher/ folder of the package (with .output/).
locate_package() {
    local here
    here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    if [[ -z "$PACKAGE" && -z "$VERSION" && -f "$here/.output/server/index.mjs" ]]; then
        SRC="$here"
        return
    fi

    command -v curl >/dev/null || die "curl is needed to download the package"
    command -v unzip >/dev/null || die "unzip is needed to extract the package (apt install unzip)"

    local url="" zip
    if [[ -n "$PACKAGE" && -f "$PACKAGE" ]]; then
        zip="$PACKAGE"
    else
        if [[ -n "$PACKAGE" ]]; then url="$PACKAGE"
        elif [[ -n "$VERSION" ]]; then url="$PACKAGE_BASE/$VERSION/netwatcher-$VERSION.zip"
        else
            log "Looking up the latest release"
            url="$(curl -fsSL --max-time 20 "$FEED_URL" | node -e '
                let s = ""; process.stdin.on("data", d => s += d).on("end", () => {
                    const u = JSON.parse(s).updates?.[0]
                    if (u?.file?.downloadUrl) console.log(u.file.downloadUrl)
                })' || true)"
            [[ -n "$url" ]] || die "no release in the feed yet: pass --version X.Y.Z or --package <zip>"
        fi
        zip="$(mktemp --suffix=.zip)"
        log "Downloading $url"
        curl -fL --progress-bar -o "$zip" "$url" || die "download failed"
    fi

    local tmp
    tmp="$(mktemp -d)"
    log "Extracting"
    unzip -q "$zip" -d "$tmp"
    [[ -f "$tmp/netwatcher/.output/server/index.mjs" ]] || die "not a NetWatcher package: netwatcher/.output/ is missing"
    SRC="$tmp/netwatcher"
}

prepare_root() {
    if [[ ! -d "$ROOT" ]]; then
        log "Creating $ROOT"
        mkdir -p "$ROOT" 2>/dev/null || { sudo mkdir -p "$ROOT" && sudo chown "$(id -un):$(id -gn)" "$ROOT"; }
    fi
    [[ -w "$ROOT" ]] || die "$ROOT is not writable by $(id -un): sudo chown $(id -un) $ROOT"
    mkdir -p "$ROOT/logs" "$ROOT/releases"
}

# Writes <root>/.env on first install. Non-interactive values: NW_PUBLIC_URL, NW_PORT, NW_HOST, NW_DATABASE_URL
# (or NW_DB_HOST/PORT/NAME/USER/PASSWORD).
configure_env() {
    local env_file="$ROOT/.env"
    if [[ -f "$env_file" ]]; then
        log "Keeping the existing $env_file"
        # An earlier first install stopped before the admin account was checked: its password is lost.
        if grep -q '^NUXT_INITIAL_ADMIN_PASSWORD_HASH=' "$env_file"; then
            sed -i '/^NUXT_INITIAL_ADMIN_PASSWORD_HASH=/d' "$env_file"
            set_initial_admin "$env_file"
        fi
        return
    fi
    log "Configuration (written to $env_file)"

    local public_url port host db_url session
    public_url="$(ask 'Public URL of the dashboard' "${NW_PUBLIC_URL:-https://netwatcher.example.com}")"
    public_url="${public_url%/}"
    port="$(ask 'Local port (the reverse proxy forwards to it)' "${NW_PORT:-5431}")"
    host="$(ask 'Listen address (0.0.0.0 if the reverse proxy is on another machine)' "${NW_HOST:-127.0.0.1}")"

    if [[ -n "${NW_DATABASE_URL:-}" ]]; then
        db_url="$NW_DATABASE_URL"
    else
        local db_host db_port db_name db_user db_pass
        db_host="$(ask 'MySQL host' "${NW_DB_HOST:-localhost}")"
        db_port="$(ask 'MySQL port' "${NW_DB_PORT:-3306}")"
        db_name="$(ask 'Database name (created if missing)' "${NW_DB_NAME:-netwatcher}")"
        db_user="$(ask 'Database user' "${NW_DB_USER:-netwatcher}")"
        db_pass="$(ask_secret 'Database password' "${NW_DB_PASSWORD:-}")"
        db_url="$(DB_USER="$db_user" DB_PASS="$db_pass" DB_HOST="$db_host" DB_PORT="$db_port" DB_NAME="$db_name" node -p '
            const e = encodeURIComponent, v = process.env;
            `mysql://${e(v.DB_USER)}:${e(v.DB_PASS)}@${v.DB_HOST}:${v.DB_PORT}/${e(v.DB_NAME)}`')"
    fi

    session="$(node -p 'require("node:crypto").randomBytes(32).toString("base64url")')"

    # Double quotes: Node's --env-file keeps $ and spaces literally inside them.
    local q='"'
    umask 077
    cat >"$env_file" <<EOF
# Written by install.sh on $(date -u +%Y-%m-%dT%H:%M:%SZ). Restart after editing: pm2 restart $APP_NAME
HOST=${q}$host${q}
PORT=${q}$port${q}
DATABASE_URL=${q}$db_url${q}
NUXT_SESSION_PASSWORD=${q}$session${q}
EOF
    umask 022
    set_initial_admin "$env_file"
}

# Generates the first admin's password (ADMIN_PASSWORD) and appends its hash to the .env: the app
# creates the "admin" account with it on an empty database. Same format as server/lib/passwords.ts.
# The line is removed once the account is checked (see check_initial_admin).
ADMIN_PASSWORD=""
set_initial_admin() {
    local hash
    ADMIN_PASSWORD="$(node -p 'require("node:crypto").randomBytes(15).toString("base64url")')"
    hash="$(PW="$ADMIN_PASSWORD" node -p '
        const c = require("node:crypto"), salt = c.randomBytes(16);
        const key = c.scryptSync(process.env.PW, salt, 64, { N: 16384, r: 8, p: 1 });
        `scrypt$16384$8$1$${salt.toString("base64url")}$${key.toString("base64url")}`')"
    printf 'NUXT_INITIAL_ADMIN_PASSWORD_HASH="%s"\n' "$hash" >>"$1"
}

env_value() { sed -n "s/^$1=\"\{0,1\}\([^\"]*\)\"\{0,1\}$/\1/p" "$ROOT/.env" | tail -1; }

install_release() {
    local version dest
    version="$(node -p "require('$SRC/package.json').version")"
    dest="$ROOT/releases/$version"
    log "Installing NetWatcher $version"

    if [[ "$SRC" != "$dest" ]]; then
        rm -rf "$dest"
        mkdir -p "$dest"
        cp -a "$SRC/." "$dest/"
    fi

    log "Applying database migrations"
    (cd "$dest" && node --env-file="$ROOT/.env" node_modules/prisma/build/index.js migrate deploy) \
        || die "migrations failed: check DATABASE_URL in $ROOT/.env (the user needs CREATE/ALTER rights)"

    log "Installing the build into $ROOT/apprun"
    rm -rf "$ROOT/apprun.prev"
    [[ -d "$ROOT/apprun" ]] && mv "$ROOT/apprun" "$ROOT/apprun.prev"
    mv "$dest/.output" "$ROOT/apprun"
    cp "$dest/ecosystem.config.cjs" "$ROOT/ecosystem.config.cjs"
    INSTALLED_VERSION="$version"
}

start_app() {
    log "Starting $APP_NAME with pm2"
    NETWATCHER_ROOT="$ROOT" pm2 startOrReload "$ROOT/ecosystem.config.cjs" --update-env
    pm2 save >/dev/null

    local port url
    port="$(env_value PORT)"
    url="http://127.0.0.1:${port:-5431}/api/categories"
    for _ in $(seq 1 30); do
        if curl -fsS -o /dev/null --max-time 3 "$url" 2>/dev/null; then
            log "NetWatcher $INSTALLED_VERSION answers on port ${port:-5431}"
            return
        fi
        sleep 1
    done
    die "the app does not answer on $url: see pm2 logs $APP_NAME"
}

# The app creates the admin account on startup: checks the new password signs in, then drops the hash.
ADMIN_CREATED=0
check_initial_admin() {
    [[ -n "$ADMIN_PASSWORD" ]] || return 0
    local port body
    port="$(env_value PORT)"
    body="$(PW="$ADMIN_PASSWORD" node -p 'JSON.stringify({ username: "admin", password: process.env.PW })')"
    for _ in $(seq 1 10); do
        if curl -fsS -o /dev/null --max-time 5 -H 'Content-Type: application/json' -d "$body" \
            "http://127.0.0.1:${port:-5431}/api/auth/login" 2>/dev/null; then
            ADMIN_CREATED=1
            break
        fi
        sleep 1
    done
    sed -i '/^NUXT_INITIAL_ADMIN_PASSWORD_HASH=/d' "$ROOT/.env"
    [[ $ADMIN_CREATED -eq 1 ]] || warn "The database already has users: no admin account was created (sign in with an existing admin)"
}

print_next_steps() {
    local port
    port="$(env_value PORT)"
    cat <<EOF

Done. Next steps:
  1. Start on boot:  pm2 startup   (run the sudo command it prints, then: pm2 save)
  2. Reverse proxy (HTTPS) to http://127.0.0.1:${port:-5431}, e.g. nginx:
       location / { proxy_pass http://127.0.0.1:${port:-5431}; proxy_set_header Host \$host;
                    proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto \$scheme; }
  3. Sign in as admin, change the password on the Account page; Administration → Update installs later versions.

Settings: $ROOT/.env (then pm2 restart $APP_NAME)   Logs: $ROOT/logs/
EOF
    if [[ $ADMIN_CREATED -eq 1 ]]; then
        cat <<EOF

Administrator account (shown only once):
  username: admin
  password: $ADMIN_PASSWORD
EOF
    fi
}

main() {
    parse_args "$@"
    check_prerequisites
    locate_package
    prepare_root
    configure_env
    install_release
    start_app
    check_initial_admin
    print_next_steps
}

main "$@"
