#!/bin/sh
# one-click-installer — ControlDeskPanel | Debian 13
# Updated  : 5.0.10 2026-11-26 01:47:15 +0100 CET — 850/867: runs with
#            "| sh" and "| bash" (restarts itself with bash)
# Updated  : 5.0.4 2026-11-25 08:43:19 +0000 UTC — 765: mktemp log/KEEP, tar, cd
# Updated : 4.6.102 2026-11-22 23:20:00 +0000 UTC — 695: CDP head first, CHANNEL_PROTECTED=0, no prompts
# Updated : 4.6.72 2026-11-19 — 497: CHANNEL_PROTECTED=0 by default
# Updated : 4.6.63 2026-11-18 12:55:00 +0000 UTC 383 OCR high
set -eu

VERSION=""
CHANNEL_BASE="https://debian13.installer.cdpcdn.com/extern/cdp"
BASE="${CDP_INSTALLER_BASE:-$CHANNEL_BASE}"
# 850/867: the code below needs bash. Started with "| sh" (dash) or
# "sh <file>", the script restarts itself with bash (file again, or
# the same script fetched from the channel when it came from a pipe).
if [ -z "${BASH_VERSION:-}" ]; then
  command -v bash >/dev/null 2>&1 || { echo "ERROR: bash is required." >&2; exit 2; }
  case "$0" in
    sh|*/sh|dash|*/dash|-sh|-dash) ;;
    *) [ -f "$0" ] && [ -r "$0" ] && exec bash "$0" "$@" ;;
  esac
  exec bash -c 'set -o pipefail; curl -fsSL "$0" | bash -s -- "$@"' "${BASE%/}/one-click-installer" "$@"
fi
NAME=""
WORKDIR=""
KEEP=""
AUTH="${CDP_INSTALLER_AUTH:-}"
CHANNEL_HOST="$(printf '%s' "$BASE" | sed -e 's#^[a-z][a-z0-9+.-]*://##' -e 's#[:/].*##')"
NETRC="${NETRC:-${HOME:-/opt/controldeskpanel}/.netrc}"
TMP_NETRC=""
CDP_INSTALL_LOG_DIR="${CDP_INSTALL_LOG_DIR:-/var/log/cdp-installer}"
CDP_RUN_CANCELLED=0

# Silent BASE validation (no output before header)
case "$BASE" in
  https://*) ;;
  *) echo "ERROR: BASE must be https://" >&2; exit 2 ;;
esac
# shellcheck disable=SC2016
if printf '%s' "$BASE" | grep -Eq '[`$"'"'"'|(){};&<> ]'; then
  echo "ERROR: invalid BASE" >&2
  exit 2
fi

netrc_cleanup() {
  [ -n "$TMP_NETRC" ] && rm -f "$TMP_NETRC" 2>/dev/null
  TMP_NETRC=""
}

netrc_has_entry() {
  [ -r "$NETRC" ] || return 1
  awk -v host="$CHANNEL_HOST" '
    { for (i = 1; i <= NF; i++) tok[++n] = $i }
    END { for (i = 1; i <= n; i++) if (tok[i] == "machine" && tok[i+1] == host) { print "1"; exit } }
  ' "$NETRC" 2>/dev/null | grep -q 1
}

netrc_auth() {
  [ -r "$NETRC" ] || return 1
  awk -v host="$CHANNEL_HOST" '
    { for (i = 1; i <= NF; i++) tok[++n] = $i }
    END {
      for (i = 1; i <= n; i++) {
        if (tok[i] == "machine" && tok[i+1] == host) {
          for (j = i + 2; j <= n; j++) {
            if (tok[j] == "machine" || tok[j] == "default") break
            if (tok[j] == "login")    u = tok[j+1]
            if (tok[j] == "password") p = tok[j+1]
          }
        }
      }
      if (u != "" && p != "") printf "%s:%s", u, p
    }
  ' "$NETRC" 2>/dev/null
}

netrc_prepare() {
  [ -n "$AUTH" ] || return 0
  [ -n "$TMP_NETRC" ] && return 0
  TMP_NETRC="$(mktemp "${TMPDIR:-/tmp}/cdp-netrc.XXXXXX")" || return 1
  chmod 600 "$TMP_NETRC"
  printf 'machine %s login %s password %s\n' \
    "$CHANNEL_HOST" "${AUTH%%:*}" "${AUTH#*:}" > "$TMP_NETRC"
}

channel_label() {
  b="${BASE%/}"
  case "$b" in
    https://debian13.installer.ctpf.network/cdp)
      printf '%s' 'internal (debian13.installer.ctpf.network/cdp)' ;;
    https://debian13.installer.cdpcdn.com/extern/cdp)
      printf '%s' 'external (debian13.installer.cdpcdn.com/extern/cdp)' ;;
    *)
      printf '%s' "${b#https://}" ;;
  esac
}

open_run_log() {
  mkdir -p "$CDP_INSTALL_LOG_DIR" 2>/dev/null || true
  CDP_INSTALL_LOG="$(mktemp "${CDP_INSTALL_LOG_DIR}/install-XXXXXX.log" 2>/dev/null)" \
    || CDP_INSTALL_LOG="$(mktemp "${TMPDIR:-/tmp}/cdp-install-XXXXXX.log")" \
    || exit 2
  chmod 0600 "$CDP_INSTALL_LOG" 2>/dev/null || true
  export CDP_INSTALL_LOG
}

emit_header() {
  role="Installer"
  ver="${VERSION:-not available}"
  ch="$(channel_label)"
  host="$(hostname -f 2>/dev/null || hostname 2>/dev/null || true)"
  [ -n "$host" ] || host="not available"
  started="$(date '+%Y-%m-%d %H:%M:%S %Z')"
  logfile="${CDP_INSTALL_LOG:-not available}"
  # Exact template — keep blank line with two spaces after copyright line.
  {
    cat <<EOF
================================================================================
  ControlDeskPanel (CDP) ${role} ${ver} for Debian 13
================================================================================
  CDP is a server control panel by Certthor Platforms Ltd.-https://certthor.com
  CDP was created by Mike Georg - https://mikegeorg.com
  CDP is copyright 2026 of Certthor Platforms Ltd. All rights reserved.
  
  Information and licences at https://controldeskpanel.com
  Support  : https://controldeskpanel.com/support
  Community: https://controldeskpanel.com/community
  
  Channel  : ${ch}
  Host     : ${host}
  Started  : ${started}
  Log file : ${logfile}

  Components are installed from their original vendor sources:
  nginx.org, packages.sury.org (PHP), mariadb.org, PGDG (PostgreSQL 19),
  Font Awesome 7.3.1, Bootstrap 5.3.9 and 6.0.0.
--------------------------------------------------------------------------------
  PLEASE READ BEFORE CONTINUING

  * A full installation takes about 20 to 40 minutes,
    an update about 10 to 25 minutes, depending on server speed.
  * Some steps (PostgreSQL migration, PHP, Docker, pgAdmin, certificates)
    can take 1 to 3 minutes without any visible output. This is normal.
  * Do NOT cancel (Ctrl+C), do NOT close the SSH session,
    do NOT reboot or power off the server while this runs.
  * If your connection drops, the run keeps going. Check the log file above.
  * A reboot is only needed if the summary at the end asks for it.
================================================================================
  Starting in 10 seconds. Press Ctrl+C now if you do not want to continue.
================================================================================
EOF
  } | tee -a "$CDP_INSTALL_LOG"
  export CDP_RUN_HEADER_DONE=1
  export CDP_RUN_ROLE="$role"
  export CDP_RUN_VERSION="$ver"
  export CDP_RUN_CHANNEL="$ch"
  export CDP_RUN_HOST="$host"
  export CDP_RUN_STARTED="$started"
  export CDP_RUN_LOGFILE="$logfile"
}

mark_cancelled() {
  CDP_RUN_CANCELLED=1
  printf 'cancelled\n' >"${CDP_INSTALL_LOG_DIR}/last-run-cancelled" 2>/dev/null || true
  echo "Cancelled. Nothing was changed." | tee -a "$CDP_INSTALL_LOG"
}

countdown() {
  if [ "${CDP_SKIP_COUNTDOWN:-0}" = "1" ]; then
    export CDP_RUN_COUNTDOWN_DONE=1
    return 0
  fi
  trap 'mark_cancelled; exit 0' INT
  sleep 10
  trap - INT
  export CDP_RUN_COUNTDOWN_DONE=1
}

# --- Auftrag 695: CHANNEL_PROTECTED=0 for both channels; never prompt ---
CHANNEL_PROTECTED=0
# Optional credentials if already present (never required, never prompted).
if [ -z "$AUTH" ] && [ -r /etc/controldeskpanel/installer-channel.auth ]; then
  AUTH="$(cat /etc/controldeskpanel/installer-channel.auth 2>/dev/null | tr -d '\r\n')" || true
fi
netrc_prepare || true

fetch_version() {
  if [ -n "$TMP_NETRC" ]; then
    curl -fsSL --netrc-file "$TMP_NETRC" "${BASE}/VERSION"
  else
    if [ -r "${HOME}/.netrc" ]; then curl -fsSL -n "${BASE}/VERSION"; else curl -fsSL "${BASE}/VERSION"; fi
  fi
}

fetch() {
  if [ -n "$TMP_NETRC" ]; then
    curl -fsSL --netrc-file "$TMP_NETRC" "$1" -o "$2"
  else
    if [ -r "${HOME}/.netrc" ]; then curl -fsSL -n "$1" -o "$2"; else curl -fsSL "$1" -o "$2"; fi
  fi
}

# Silent metadata: version + log, then header (first process output)
VERSION="$(fetch_version 2>/dev/null | tr -d '\r\n ' || true)"
[ -n "$VERSION" ] || VERSION="not available"
open_run_log
emit_header
if [ "$VERSION" = "not available" ]; then
  echo "ERROR: could not read the version from the channel (${BASE}/VERSION)." | tee -a "$CDP_INSTALL_LOG" >&2
  echo "Cause : VERSION missing or channel unreachable without interactive credentials." | tee -a "$CDP_INSTALL_LOG" >&2
  echo "Fix   : ensure ${BASE}/VERSION is reachable over HTTPS, then re-run this command." | tee -a "$CDP_INSTALL_LOG" >&2
  exit 2
fi
case "$VERSION" in
  *[!0-9.]*)
    echo "ERROR: implausible version from the channel: '${VERSION}'" | tee -a "$CDP_INSTALL_LOG" >&2
    exit 2 ;;
esac
countdown

NAME="cdp-installer-${VERSION}"
case "$NAME" in
  *[!A-Za-z0-9._-]*) echo "ERROR: invalid package name" >&2; exit 2 ;;
esac
umask 077
WORKDIR="$(mktemp -d "${TMPDIR:-/tmp}/cdp-installer.XXXXXX")" || {
  echo "ERROR: mktemp failed" >&2; exit 2
}
_oci_cleanup() {
  [ -n "${WORKDIR:-}" ] && rm -rf "$WORKDIR"
  [ -n "${_snap:-}" ] && rm -f "$_snap"
  [ -n "${_list:-}" ] && rm -f "$_list"
  netrc_cleanup
}
trap '_oci_cleanup' EXIT INT TERM

fetch "${BASE}/releases/${NAME}.tgz" "$WORKDIR/${NAME}.tgz"
fetch "${BASE}/releases/${NAME}.tgz.sha256" "$WORKDIR/${NAME}.tgz.sha256"

expected="$(awk '{print $1}' "$WORKDIR/${NAME}.tgz.sha256")"
actual="$(sha256sum "$WORKDIR/${NAME}.tgz" | awk '{print $1}')"
if [ -z "$expected" ] || [ "$expected" != "$actual" ]; then
  echo "ERROR: SHA-256 mismatch. Aborting." >&2
  echo "expected=${expected}" >&2
  echo "actual=${actual}" >&2
  exit 22
fi

KEEP="$(mktemp -d "${TMPDIR:-/tmp}/cdp-install-keep.XXXXXX")" || {
  echo "ERROR: mktemp KEEP failed" >&2; exit 21
}
chmod 700 "$KEEP"
_snap="$(mktemp "${TMPDIR:-/tmp}/cdp-tar-snap.XXXXXX")" || { echo "ERROR: mktemp failed" >&2; exit 21; }
cp -f "$WORKDIR/${NAME}.tgz" "$_snap" || { rm -f "$_snap"; echo "ERROR: tar snapshot failed" >&2; exit 21; }
while IFS= read -r _m; do
  [ -z "$_m" ] && continue
  case "$_m" in
    /*|~*) rm -f "$_snap"; echo "ERROR: unsafe archive member: $_m" >&2; exit 23 ;;
  esac
  case "/$_m/" in
    */../*) rm -f "$_snap"; echo "ERROR: unsafe archive member: $_m" >&2; exit 23 ;;
  esac
  _lt="${_m#* -> }"
  if [ "$_lt" != "$_m" ]; then
    case "$_lt" in /*|~*) rm -f "$_snap"; echo "ERROR: unsafe archive link: $_m" >&2; exit 23 ;; esac
    case "/$_lt/" in */../*) rm -f "$_snap"; echo "ERROR: unsafe archive link: $_m" >&2; exit 23 ;; esac
  fi
done <<CDP_TAR_LIST
$(tar -tzf "$_snap")
CDP_TAR_LIST
tar -xzf "$_snap" -C "$KEEP" || { rm -f "$_snap"; exit 23; }
rm -f "$_snap"
if [ -x "$KEEP/${NAME}/install.sh" ]; then
  RUN="$KEEP/${NAME}"
else
  inner="$(find "$KEEP" -maxdepth 3 -name install.sh -type f | head -n 1)"
  [ -n "$inner" ] || { echo "ERROR: install.sh missing in package" >&2; exit 40; }
  RUN="$(dirname "$inner")"
fi
_kroot="$(cd "$KEEP" && pwd)"
_krun="$(cd "$RUN" && pwd)"
case "$_krun" in
  "$_kroot"/*) ;;
  *) echo "ERROR: install.sh outside package dir" >&2; exit 23 ;;
esac

( umask 077
  mkdir -p -m 0700 /etc/controldeskpanel
  printf '%s\n' "$BASE" > /etc/controldeskpanel/installer-channel.url
  chmod 0644 /etc/controldeskpanel/installer-channel.url ) 2>/dev/null || true

STORE_AUTH="$AUTH"
if [ -z "$STORE_AUTH" ] && netrc_has_entry; then
  STORE_AUTH="$(netrc_auth)"
fi
# Do not create or overwrite auth files from prompts (none exist). Keep existing only.
if [ -n "$STORE_AUTH" ] && [ ! -e /etc/controldeskpanel/installer-channel.auth ]; then
  ( umask 077
    mkdir -p -m 0700 /etc/controldeskpanel
    printf '%s\n' "$STORE_AUTH" > /etc/controldeskpanel/installer-channel.auth
    chmod 0600 /etc/controldeskpanel/installer-channel.auth ) 2>/dev/null || true
fi

rm -rf "$WORKDIR"
WORKDIR=""
unset AUTH pw STORE_AUTH

cd "$RUN" || { echo "ERROR: cannot cd to package" >&2; exit 21; }
chmod +x ./install.sh ./update.sh 2>/dev/null || true
# Nested install inherits header/countdown/log; always unattended (no prompts).
export CDP_RUN_HEADER_DONE=1
export CDP_RUN_COUNTDOWN_DONE=1
export CDP_INSTALL_LOG
exec ./install.sh --one-click --unattended "$@" </dev/null
