#!/usr/bin/env bash
# SPDX-License-Identifier: LicenseRef-CMSD-1.0
# SecuBox-Deb :: peertubectl
# CyberMind — https://cybermind.fr
#
# PeerTube host-side controller. PeerTube runs NATIVELY in a Debian LXC
# (default 10.100.0.120 on br-lxc, peertube.service inside the container).
# The host nginx vhost proxies the public hostname to <LXC_IP>:9000.
#
# Conventions: docs/MODULE-GUIDELINES.md §7 (mirror of grafanactl/giteactl).

set -u

readonly VERSION="1.1.0"
readonly CONFIG_FILE="${SECUBOX_PEERTUBE_CONFIG:-/etc/secubox/peertube.toml}"
readonly INSTALL_LIB="${SECUBOX_INSTALL_LIB:-/usr/share/secubox/lib/peertube/install-lxc.sh}"

readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly NC='\033[0m'

log()  { printf '%b[peertube]%b %s\n' "$GREEN" "$NC" "$*"; }
warn() { printf '%b[warn]%b %s\n'    "$YELLOW" "$NC" "$*" >&2; }
err()  { printf '%b[error]%b %s\n'   "$RED"    "$NC" "$*" >&2; }

# ── TOML config (best-effort, grep-style — same as giteactl/grafanactl) ──────
config_get() {
    local key="$1" default="${2:-}" raw=""
    if [ -f "$CONFIG_FILE" ]; then
        raw=$(grep -E "^[[:space:]]*${key}[[:space:]]*=" "$CONFIG_FILE" 2>/dev/null | head -1)
    fi
    if [ -z "$raw" ]; then echo "$default"; return; fi
    local val
    val=$(echo "$raw" | cut -d= -f2- | sed 's/[[:space:]]*#.*$//' \
        | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//' | tr -d '"' | tr -d "'")
    [ -z "$val" ] && echo "$default" || echo "$val"
}

LXC_NAME=$(config_get "name" "peertube")
LXC_IP=$(config_get "ip" "10.100.0.120")
LXC_PATH=$(config_get "path" "/data/lxc")
HTTP_PORT=$(config_get "http_port" "9000")
PUBLIC_HOSTNAME=$(config_get "public_hostname" "peertube.gk2.secubox.in")

# ── LXC helpers ───────────────────────────────────────────────────────────────
lxc_state() {
    lxc-info -n "$LXC_NAME" -P "$LXC_PATH" 2>/dev/null \
        | awk -F: '/^State:/ { gsub(/ /,"",$2); print tolower($2) }'
}
lxc_running() { [ "$(lxc_state)" = "running" ]; }
svc() { lxc-attach -n "$LXC_NAME" -P "$LXC_PATH" -- systemctl "$@" peertube.service; }

# ── Verbs ─────────────────────────────────────────────────────────────────────
cmd_install() {
    if [ ! -x "$INSTALL_LIB" ] && [ ! -f "$INSTALL_LIB" ]; then
        err "install script not found at $INSTALL_LIB (package not installed correctly?)"
        exit 1
    fi
    log "Running LXC bootstrap from $INSTALL_LIB ..."
    SECUBOX_LXC_NAME="$LXC_NAME" SECUBOX_LXC_IP="$LXC_IP" SECUBOX_LXC_PATH="$LXC_PATH" \
    SECUBOX_PEERTUBE_HOSTNAME="$PUBLIC_HOSTNAME" \
        bash "$INSTALL_LIB"
    log "Done. Try 'peertubectl status' to verify, then wire the nginx vhost + HAProxy ACL."
}

cmd_status() {
    local state; state="$(lxc_state)"
    printf 'LXC %s        : %s\n' "$LXC_NAME" "${state:-absent}"
    if lxc_running; then
        local active; active="$(svc is-active 2>/dev/null || true)"
        printf 'peertube.service : %s\n' "${active:-unknown}"
        if curl -fsS -o /dev/null --max-time 3 "http://$LXC_IP:$HTTP_PORT/api/v1/config" 2>/dev/null; then
            printf 'HTTP %s:%s   : responding\n' "$LXC_IP" "$HTTP_PORT"
        else
            printf 'HTTP %s:%s   : NOT responding\n' "$LXC_IP" "$HTTP_PORT"
        fi
    fi
    printf 'public URL       : https://%s/\n' "$PUBLIC_HOSTNAME"
}

cmd_start()   { lxc_running || lxc-start -n "$LXC_NAME" -P "$LXC_PATH"; svc start;   log "started"; }
cmd_stop()    { lxc_running && svc stop || true;                                     log "stopped"; }
cmd_restart() { lxc_running || lxc-start -n "$LXC_NAME" -P "$LXC_PATH"; svc restart; log "restarted"; }
cmd_logs()    { lxc-attach -n "$LXC_NAME" -P "$LXC_PATH" -- journalctl -u peertube -n "${1:-50}" --no-pager; }

cmd_reload() {
    if nginx -t 2>/dev/null; then
        systemctl reload nginx 2>/dev/null && log "host nginx reloaded" || warn "nginx reload failed"
    else
        err "nginx -t failed; not reloading"; exit 1
    fi
}

cmd_set_youtube_cookies() {
    # Install a Netscape-format cookies.txt (exported from a browser logged into
    # YouTube) so PeerTube's yt-dlp import can fetch YouTube videos. YouTube
    # hard-blocks server IPs ("Sign in to confirm you're not a bot") — cookies
    # are the only reliable workaround. Idempotent.
    local src="${1:-}"
    [ -n "$src" ] && [ -f "$src" ] || { err "usage: peertubectl set-youtube-cookies <cookies.txt>"; exit 1; }
    lxc_running || { err "LXC '$LXC_NAME' not running"; exit 1; }
    log "Installing YouTube cookies into $LXC_NAME ..."
    lxc-attach -n "$LXC_NAME" -P "$LXC_PATH" -- bash -c '
        d=/var/www/peertube/storage/tmp-persistent
        install -d -o peertube -g peertube "$d"
        cat > "$d/youtube-cookies.txt"
        chown peertube:peertube "$d/youtube-cookies.txt"
        chmod 600 "$d/youtube-cookies.txt"
    ' < "$src"
    # Ensure the cookies feature is enabled in production.yaml.
    lxc-attach -n "$LXC_NAME" -P "$LXC_PATH" -- python3 - <<'PY'
import re, pathlib
p = pathlib.Path('/var/www/peertube/config/production.yaml')
lines = p.read_text().splitlines()
ind = lambda s: len(s) - len(s.lstrip())
imp=vid=http=ck=False; chg=False
for i,l in enumerate(lines):
    if re.match(r'^import\s*:', l) and ind(l)==0: imp=True; vid=http=ck=False; continue
    if imp and l and ind(l)==0 and not l.startswith('#'): imp=vid=http=ck=False
    if imp and re.match(r'^\s+videos\s*:', l): vid=True; http=ck=False; continue
    if imp and vid and re.match(r'^\s+http\s*:', l): http=True; ck=False; continue
    if imp and vid and http and re.match(r'^\s+cookies\s*:', l): ck=True; continue
    if ck and re.match(r'^\s+enabled\s*:', l): lines[i]=l[:ind(l)]+'enabled: true'; ck=False; chg=True
p.write_text('\n'.join(lines)+'\n')
print('cookies enabled' if chg else 'cookies flag unchanged')
PY
    log "Cookies installed + enabled. Restarting PeerTube ..."
    svc restart
    log "Done. Retry the import from the PeerTube 'Import with URL' page."
}

cmd_help() {
    cat <<EOF
peertubectl $VERSION — SecuBox PeerTube (native-LXC) controller

Usage: peertubectl <verb> [args]

  install                       Provision the LXC + install PeerTube (idempotent)
  status                        LXC state + peertube.service + HTTP reachability
  start|stop|restart            Control peertube.service inside the LXC
  set-youtube-cookies <file>    Install browser-exported YouTube cookies.txt so
                                yt-dlp import works (YouTube blocks server IPs)
  logs [N]                      Tail N lines of peertube journal (default 50)
  reload                        Reload host nginx (after vhost changes)
  help                          This message

Config: $CONFIG_FILE  (name/ip/path/http_port/public_hostname)
LXC: $LXC_NAME @ $LXC_IP on br-lxc — public https://$PUBLIC_HOSTNAME/
EOF
}

main() {
    local noun="${1:-help}"; shift || true
    case "$noun" in
        install|status|start|stop|restart|logs|reload) "cmd_${noun}" "$@" ;;
        set-youtube-cookies) cmd_set_youtube_cookies "$@" ;;
        help|-h|--help) cmd_help ;;
        *) err "unknown verb: $noun"; cmd_help; exit 1 ;;
    esac
}

main "$@"
