#!/usr/bin/env bash
#
# MeshCord Node — one-command installer
#
#   curl -fsSL https://meshcordapp.xyz/install.sh | sudo bash
#
# What it does:
#   1. Verifies the host (Linux, root/sudo, ports 80/443 free-ish).
#   2. Installs Docker + the compose plugin if missing.
#   3. Downloads the MeshCord server bundle from the release host and
#      verifies its SHA-256 checksum.
#   4. Generates per-node secrets (JWT, API key, node + bot secrets).
#   5. Renders the Caddyfile, then `docker compose up -d --build`.
#   6. Waits for https://<DOMAIN>/health and prints next steps.
#
# Non-interactive use:
#   sudo DOMAIN=node.example.com ACME_EMAIL=ops@example.com bash install.sh
#   sudo bash install.sh --domain node.example.com --email ops@example.com
#
set -euo pipefail

RED=$'\e[1;31m'; GREEN=$'\e[1;32m'; YELLOW=$'\e[1;33m'; BLUE=$'\e[1;36m'; BOLD=$'\e[1m'; NC=$'\e[0m'
info() { echo "${BLUE}[*]${NC} $*"; }
ok()   { echo "${GREEN}[✓]${NC} $*"; }
warn() { echo "${YELLOW}[!]${NC} $*"; }
err()  { echo "${RED}[✗]${NC} $*" >&2; }

# ── Configuration ─────────────────────────────────────────────────────────────
# Downloads come from the MeshCord release host by default; the website backend
# rewrites this origin when it serves the script, and MESHCORD_FILES_BASE
# overrides it for mirrors/testing.
FILES_BASE="${MESHCORD_FILES_BASE:-https://meshcordapp.xyz}"
INSTALL_DIR="${MESHCORD_DIR:-/opt/meshcord}"
DOMAIN="${DOMAIN:-}"
ACME_EMAIL="${ACME_EMAIL:-}"
# TLS_MODE=caddy    — bundled Caddy terminates TLS (default, standalone VPS)
# TLS_MODE=external — you terminate TLS yourself (NPM etc.); node listens on NODE_PORT
TLS_MODE="${TLS_MODE:-caddy}"
NODE_PORT="${NODE_PORT:-3000}"
ASSUME_YES=0

usage() {
    cat <<EOF
MeshCord Node installer

  sudo bash install.sh [--domain FQDN] [--email EMAIL] [--yes]

Environment variables:  DOMAIN, ACME_EMAIL, MESHCORD_FILES_BASE, MESHCORD_DIR
EOF
}

while [ $# -gt 0 ]; do
    case "$1" in
        --domain) DOMAIN="$2"; shift 2 ;;
        --email)  ACME_EMAIL="$2"; shift 2 ;;
        --yes|-y) ASSUME_YES=1; shift ;;
        --help|-h) usage; exit 0 ;;
        *) err "Unknown option: $1"; usage; exit 1 ;;
    esac
done

# ── Preconditions ─────────────────────────────────────────────────────────────
require_root() {
    if [ "${EUID:-$(id -u)}" -ne 0 ]; then
        if command -v sudo >/dev/null 2>&1 && [ -f "$0" ] && [ -r "$0" ]; then
            info "Re-running under sudo…"
            exec sudo DOMAIN="$DOMAIN" ACME_EMAIL="$ACME_EMAIL" \
                 MESHCORD_FILES_BASE="$FILES_BASE" MESHCORD_DIR="$INSTALL_DIR" \
                 TLS_MODE="$TLS_MODE" NODE_PORT="$NODE_PORT" \
                 bash "$0" --yes
        fi
        err "Must run as root. Pipe form:  curl -fsSL <host>/install.sh | sudo bash"
        exit 1
    fi
}

IS_DSM=0
DC="docker compose"

check_os() {
    if [ "$(uname -s)" != "Linux" ]; then
        err "This installer targets Linux. On macOS/Windows run Docker Desktop and:"
        err "  docker compose -f deploy/docker-compose.yml up -d --build"
        exit 1
    fi
    # Synology DSM (incl. ARC loader): synopkg + /etc/VERSION identify it.
    if command -v synopkg >/dev/null 2>&1 || [ -f /etc/VERSION ]; then
        IS_DSM=1
        ok "Synology DSM detected"
        return
    fi
    command -v apt-get >/dev/null 2>&1 || command -v dnf >/dev/null 2>&1 \
        || command -v yum >/dev/null 2>&1 || command -v pacman >/dev/null 2>&1 \
        || warn "Unrecognised package manager — assuming Docker is already installed."
}

gen_secret() {
    if command -v openssl >/dev/null 2>&1; then
        openssl rand -hex 48
    else
        head -c 48 /dev/urandom | od -An -tx1 | tr -d ' \n'
    fi
}

# ── Docker ────────────────────────────────────────────────────────────────────
ensure_docker() {
    info "Checking Docker…"
    # DSM ships docker inside the Container Manager package — surface its bin dirs.
    if [ "$IS_DSM" -eq 1 ]; then
        for d in /usr/local/bin \
                 /var/packages/ContainerManager/target/usr/bin \
                 /var/packages/Docker/target/usr/bin; do
            [ -x "$d/docker" ] && PATH="$PATH:$d"
        done
        export PATH
        command -v docker >/dev/null 2>&1 || {
            err "Docker not found — install Container Manager (or Docker) from Package Center."
            exit 1
        }
    elif ! command -v docker >/dev/null 2>&1; then
        info "Installing Docker via the official convenience script…"
        curl -fsSL https://get.docker.com -o /tmp/get-docker.sh
        sh /tmp/get-docker.sh
        rm -f /tmp/get-docker.sh
        systemctl enable --now docker >/dev/null 2>&1 || true
    fi

    DOCKER_TIMEOUT=""
    command -v timeout >/dev/null 2>&1 && DOCKER_TIMEOUT="timeout 10"

    if $DOCKER_TIMEOUT docker compose version >/dev/null 2>&1; then
        DC="docker compose"
    elif command -v docker-compose >/dev/null 2>&1 \
         && $DOCKER_TIMEOUT docker-compose version >/dev/null 2>&1; then
        DC="docker-compose"
    else
        err "Docker Compose not found (need compose v2 plugin or docker-compose)."
        exit 1
    fi
    ok "Docker present ($DC)"
}

# ── Prompts ───────────────────────────────────────────────────────────────────
# Only ask anything when the operator is driving interactively — i.e. DOMAIN was
# not supplied via env/flag. A provided DOMAIN means scripted use: never block.
INTERACTIVE=0
prompt_domain() {
    if [ -z "$DOMAIN" ]; then
        if [ "$ASSUME_YES" -eq 1 ]; then
            err "DOMAIN is required in non-interactive mode (--domain or DOMAIN env)."
            exit 1
        fi
        read -r -p "$(echo -e "${BOLD}Public domain for this node (e.g. node.example.com):${NC} ")" DOMAIN < /dev/tty \
            || { err "No terminal for prompts — pass --domain or DOMAIN env instead."; exit 1; }
        INTERACTIVE=1
    fi
    case "$DOMAIN" in
        ""|*[!a-zA-Z0-9.-]*|*..*)
            err "Invalid domain: '$DOMAIN'"
            exit 1 ;;
    esac
    ok "Domain: $DOMAIN (TLS_MODE=$TLS_MODE NODE_PORT=$NODE_PORT)"

    # ACME email is only relevant when the bundled Caddy terminates TLS — and we
    # only ask interactively. Times out after 30s so it can never stall a run.
    if [ "$INTERACTIVE" -eq 1 ] && [ -z "$ACME_EMAIL" ] && [ "$TLS_MODE" != "external" ]; then
        read -r -t 30 -p "$(echo -e "${BOLD}Email for Let's Encrypt notices (optional, Enter to skip):${NC} ")" ACME_EMAIL < /dev/tty || true
    fi
}

# ── Bundle download + verify ──────────────────────────────────────────────────
download_bundle() {
    info "Locating bundle…"
    # If we're running from inside an already-extracted bundle
    # (deploy/install.sh with server/ + meshbot/ next to it), use it in place.
    local script_dir
    script_dir="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd || true)"
    if [ -n "$script_dir" ] && [ -f "$script_dir/docker-compose.yml" ] \
       && [ -d "$script_dir/../server" ] && [ -d "$script_dir/../meshbot" ]; then
        INSTALL_DIR="$(cd "$script_dir/.." && pwd)"
        ok "Using local bundle at $INSTALL_DIR"
        return
    fi
    # Running from a served-site tree? The published bundle is right here —
    # no network needed (avoids hairpin-NAT issues on the host itself).
    if [ -f "$script_dir/files/meshcord-bundle.tar.gz" ]; then
        mkdir -p "$INSTALL_DIR"
        tar -xzf "$script_dir/files/meshcord-bundle.tar.gz" -C "$INSTALL_DIR"
        ok "Used local bundle $script_dir/files/meshcord-bundle.tar.gz → $INSTALL_DIR"
        return
    fi
    mkdir -p "$INSTALL_DIR"
    cd "$INSTALL_DIR"
    info "Downloading MeshCord bundle from $FILES_BASE…"
    curl -fsSL --connect-timeout 15 --max-time 300 "$FILES_BASE/files/meshcord-bundle.tar.gz"    -o meshcord-bundle.tar.gz
    curl -fsSL --connect-timeout 15 --max-time 60  "$FILES_BASE/files/sha256sums.txt" -o sha256sums.txt
    info "Verifying checksum…"
    grep 'meshcord-bundle.tar.gz' sha256sums.txt | sha256sum -c - || {
        err "Checksum verification failed — aborting."
        exit 1
    }
    ok "Checksum verified"
    tar -xzf meshcord-bundle.tar.gz
    rm -f meshcord-bundle.tar.gz
    ok "Bundle extracted to $INSTALL_DIR"
}

# ── Env + Caddyfile ───────────────────────────────────────────────────────────
write_env() {
    info "Writing configuration…"
    cd "$INSTALL_DIR/deploy"
    set_env() {  # update KEY= in place, or append if absent
        grep -q "^$2=" .env 2>/dev/null \
            && sed -i "s|^$2=.*|$2=$1|" .env \
            || echo "$2=$1" >> .env
    }
    if [ -f .env ]; then
        warn "Existing .env found — keeping current secrets/config."
        # DOMAIN/ports may have changed; refresh them anyway.
        set_env "$DOMAIN" DOMAIN
        set_env "$NODE_PORT" NODE_PORT
        set_env "$TLS_MODE" TLS_MODE
        return
    fi
    sed -e "s/^DOMAIN=.*/DOMAIN=$DOMAIN/" \
        -e "s/^ACME_EMAIL=.*/ACME_EMAIL=$ACME_EMAIL/" \
        -e "s/^NODE_SECRET=.*/NODE_SECRET=$(gen_secret)/" \
        -e "s/^JWT_SECRET=.*/JWT_SECRET=$(gen_secret)/" \
        -e "s/^LOCAL_API_KEY=.*/LOCAL_API_KEY=$(gen_secret)/" \
        -e "s/^BOT_SECRET=.*/BOT_SECRET=$(gen_secret)/" \
        .env.example > .env
    echo "NODE_PORT=$NODE_PORT" >> .env
    echo "TLS_MODE=$TLS_MODE" >> .env
    chmod 600 .env
    ok "Generated .env with fresh secrets (mode 600)"
}

render_caddyfile() {
    cd "$INSTALL_DIR/deploy"
    {
        if [ -n "$ACME_EMAIL" ]; then
            printf '{\n    email %s\n}\n\n' "$ACME_EMAIL"
        fi
        cat Caddyfile.template
    } > Caddyfile
    ok "Caddyfile rendered for $DOMAIN"
}

# ── Launch ────────────────────────────────────────────────────────────────────
launch() {
    cd "$INSTALL_DIR/deploy"
    info "Building and starting the stack (first build takes a few minutes)…"
    if [ "$TLS_MODE" = "external" ]; then
        $DC --env-file .env -f docker-compose.yml up -d --build server meshbot
    else
        $DC --env-file .env -f docker-compose.yml --profile edge up -d --build
    fi
    ok "Containers started"
}

wait_health() {
    if [ "$TLS_MODE" = "external" ]; then
        info "Checking node on http://127.0.0.1:$NODE_PORT/health …"
        for i in $(seq 1 24); do
            curl -fsS -m 5 "http://127.0.0.1:$NODE_PORT/health" >/dev/null 2>&1 && {
                ok "Node API is live on :$NODE_PORT"
                return 0
            }
            sleep 5
        done
        warn "Node health check timed out — check: $DC -f $INSTALL_DIR/deploy/docker-compose.yml logs"
        return 0
    fi
    info "Waiting for https://$DOMAIN/health (ACME issuance can take ~60s)…"
    for i in $(seq 1 36); do
        if curl -fsS -m 5 "https://$DOMAIN/health" >/dev/null 2>&1; then
            ok "Node is live at https://$DOMAIN"
            return 0
        fi
        sleep 5
    done
    warn "Health check timed out — check: $DC -f $INSTALL_DIR/deploy/docker-compose.yml logs"
    warn "Common cause: DNS for $DOMAIN not pointing at this host, or ports 80/443 blocked."
}

print_done() {
    cat <<EOF

${GREEN}${BOLD}MeshCord node installed.${NC}

  URL:        https://$DOMAIN$([ "$TLS_MODE" = "external" ] && echo "  (via your TLS proxy → http://$(hostname -I | awk '{print $1}'):$NODE_PORT)")
  Data:       $INSTALL_DIR (docker volumes: server-data, meshbot-data)
  Config:     $INSTALL_DIR/deploy/.env
  Logs:       $DC -f $INSTALL_DIR/deploy/docker-compose.yml logs -f
  Dashboard:  ssh -L 4001:localhost:4001 <this host>  →  http://localhost:4001

${BOLD}Next:${NC} open the MeshCord app, enter ${BOLD}https://$DOMAIN${NC},
and create your Master Admin account.

EOF
}

main() {
    echo "${BOLD}━━━ MeshCord Node Installer ━━━${NC}"
    require_root
    check_os
    prompt_domain
    ensure_docker
    download_bundle
    write_env
    [ "$TLS_MODE" = "external" ] || render_caddyfile
    launch
    wait_health
    print_done
}

main "$@"
