#!/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), NW_OIDC_CLIENT_ID, NW_OIDC_CLIENT_SECRET, NW_OIDC_CONFIG, NW_ADMIN_EMAILS.
configure_env() {
    local env_file="$ROOT/.env"
    if [[ -f "$env_file" ]]; then
        log "Keeping the existing $env_file"
        return
    fi
    log "Configuration (written to $env_file)"

    local public_url port host db_url client_id client_secret oidc_config admins 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

    echo "Teslina sign-in: create an OIDC client with redirect URL $public_url/api/oauth/teslina/callback"
    client_id="$(ask 'OIDC client id' "${NW_OIDC_CLIENT_ID:-}")"
    client_secret="$(ask_secret 'OIDC client secret (empty for a public PKCE client)' "${NW_OIDC_CLIENT_SECRET:-}")"
    oidc_config="$(ask 'OIDC discovery URL' "${NW_OIDC_CONFIG:-https://services.teslina.net/.well-known/openid-configuration}")"
    admins="$(ask 'Admin emails, comma-separated (promoted on first sign-in)' "${NW_ADMIN_EMAILS:-}")"
    session="$(node -p 'require("node:crypto").randomBytes(32).toString("base64url")')"

    [[ -n "$client_id" ]] || warn "No OIDC client id: sign-in will not work until NUXT_OAUTH_OIDC_CLIENT_ID is set in $env_file"
    [[ -n "$admins" ]] || warn "No admin email: nobody can open the administration until NUXT_BOOTSTRAP_ADMIN_EMAILS is set"

    # 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}
NUXT_OAUTH_OIDC_CLIENT_ID=${q}$client_id${q}
NUXT_OAUTH_OIDC_CLIENT_SECRET=${q}$client_secret${q}
NUXT_OAUTH_OIDC_OPENID_CONFIG=${q}$oidc_config${q}
NUXT_OAUTH_OIDC_REDIRECT_URL=${q}$public_url/api/oauth/teslina/callback${q}
NUXT_BOOTSTRAP_ADMIN_EMAILS=${q}$admins${q}
EOF
    umask 022
}

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"
}

print_next_steps() {
    local redirect port
    redirect="$(env_value NUXT_OAUTH_OIDC_REDIRECT_URL)"
    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. OIDC client redirect URL: ${redirect:-<public URL>/api/oauth/teslina/callback}
  4. Sign in with an admin email, then Administration → Update installs later versions.

Settings: $ROOT/.env (then pm2 restart $APP_NAME)   Logs: $ROOT/logs/
EOF
}

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

main "$@"
