#!/bin/sh
# one-click-updater — ControlDeskPanel | bootstrap for Ubuntu 26.04
# Version  : 4.0.5 2026-11-05 14:04:48 +0100 CET — 2189: OS channel
# Updated  : 4.5.70 2026-11-20 11:27:37 +0000 UTC — 512: one layout for
#            both channels (like Debian 13), package by VERSION-ubuntu26
# Updated  : 4.5.78 2026-11-21 20:15:27 +0100 CET — 641: always
#            unattended, stdin empty (no question with a TTY)
# Updated  : 4.5.79 2026-11-21 23:49:18 +0100 CET — 646: checked downloads
#            against the GnuPG-signed checksum manifest of the release
#            (lib/channel-fetch.sh), channel of an installation only from
#            installation data, never a channel switch
# Updated  : 5.0.0 2026-11-24 22:31:35 +0100 CET — 755: mandatory header
#            (lib/cdp-run-header.sh) as first output, then 10 s countdown;
#            internal channel without credentials (no -u, no netrc)
# Updated  : 5.0.1 2026-11-25 07:56:37 +0000 UTC — 764: mktemp, tar and cd
#            checked with cause, unpack directory removed on any stop
# Updated  : 5.0.3 2026-11-25 13:24:21 +0100 CET — 781: CLI fallback of
#            Tools > CDP Update: installed as /usr/local/sbin/cdp-update,
#            "cdp-update --now" runs this same checked update, --help
#            prints the usage; without arguments unchanged (curl ... | sh)
# Updated  : 5.0.3 2026-11-25 15:08:02 +0100 CET — 781: no downgrade: a
#            channel older than the installed version stops the update
#            before any download (same version = repair run allowed)
# Updated  : 5.0.7 2026-11-25 15:26:37 +0100 CET — 788: only the updater of
#            the package top folder cdp-installer-*/update.sh is started
# Updated  : 5.0.7 2026-11-25 16:46:30 +0100 CET — 824: header and
#            --version show the version of this updater (KANAL_BOOT_
#            VERSION, set by tools/build.sh from VERSION), not the
#            channel's; a channel older than the installed version ends
#            with "Channel version X is older than installed Y - no
#            update" (exit 26, no ERROR line), also in the run log
# Infos    : update of an installed server. Run as root:
#              curl -fsSL <channel>/one-click-updater | sh
#            The channel decides the version (VERSION-ubuntu26). Manifest,
#            signature and package are checked completely before
#            update.sh is started; any failed check stops with cause, fix
#            and retry command and runs nothing. tools/build.sh writes the
#            KANAL_* values of the edition and the release key below.
set -eu

# 781: cdp-update --now / --help (no argument: as before)
case "${1:-}" in
  -h|--help)
    cat <<'USAGE'
Usage: cdp-update --now
       cdp-update --version
       cdp-update --help

Runs the regular ControlDeskPanel update now, in the foreground and as
root: the same checked update (channel of this installation, signed
manifest, SHA-256) that the panel button Tools > CDP Update starts in the
background. Only one run at a time (lock /run/lock/cdp-installer.lock).
Log: /var/log/cdp-installer/
USAGE
    exit 0
    ;;
  --now) shift ;;
  # 824: print the version of this updater and run nothing
  -V|--version) CDP_BOOT_SHOW_VERSION=1 ;;
esac

KANAL_BASIS="https://ubuntu26.installer.cdpcdn.com/extern/cdp"
KANAL_EDITION="extern"
KANAL_URL_INTERN="https://ubuntu26.installer.ctpf.network/cdp"
KANAL_URL_EXTERN="https://ubuntu26.installer.cdpcdn.com/extern/cdp"
KANAL_KEY_FPR="85957A10ACC290335A0B7B62D29717CA2274A85B"
# 824: version of this updater (tools/build.sh, from VERSION)
KANAL_BOOT_VERSION="5.0.12"
KANAL_KEY_B64="mDMEawIKLBYJKwYBBAHaRw8BAQdAk9PF2AS13yosTyyv/1jzoMiV/OxLQi+Bu0HGqSKQCm+0VUNEUCBVYnVudHUgMjYuMDQgUmVsZWFzZSBTaWduaW5nICh1YnVudHUyNi5pbnN0YWxsZXIpIDxyZWxlYXNlLXVidW50dTI2QGN0cGYubmV0d29yaz6IlgQTFgoAPhYhBIWVehCswpAzWgt7YtKXF8oidKhbBQJrAgosAhsDBQkJZgGABQsJCAcCBhUKCQgLAgQWAgMBAh4BAheAAAoJENKXF8oidKhbHDcBALwOzLn5KCdDNLRqpMRyjBnw01f9fHEc04JdUUIP+3UrAQD5+J+yJ0JbxCUnD/xsee1IbfxtWffjajX29s9qVqIZAw=="
OS_KEY_WANT="ubuntu26"
# 755: like Debian (497/695): both channels open, never a password prompt
CHANNEL_PROTECTED=0
CDP_BOOT_MODE="update"
if [ "${CDP_BOOT_SHOW_VERSION:-0}" = "1" ]; then
  printf 'ControlDeskPanel (CDP) Updater %s for Ubuntu 26.04\n' \
    "${KANAL_BOOT_VERSION:-not available}"
  exit 0
fi

# >>> lib/cdp-run-header.sh
# lib/cdp-run-header.sh — ControlDeskPanel | run header and countdown
# =====================================================================
# Project  : ControlDeskPanel by CTPF Certthor Platforms Ltd.
# Author   : MikeGeorg / Senior Full-Stack Developer and Team
# Version  : 5.0.0 2026-11-24 22:31:35 +0100 CET — 755: mandatory header
#            (Michael 22.11.2026, 4.6.100 block) for Ubuntu 26.04, first
#            output of every installer and updater run, intern and extern
# Layout   : lib/cdp-run-header.sh (POSIX sh). tools/build.sh copies this
#            file between the markers into one-click-installer and
#            one-click-updater; install.sh and update.sh source it.
# Infos    : Exactly one header and one 10 s countdown per run. The
#            bootstrap prints them and exports CDP_RUN_HEADER_DONE=1 and
#            CDP_INSTALL_LOG, so install.sh/update.sh started by it print
#            nothing twice and write into the same log. Called directly,
#            install.sh/update.sh print the header themselves.
#            CDP_SKIP_COUNTDOWN=1 only for the test harness.

: "${CDP_INSTALL_LOG_DIR:=/var/log/cdp-installer}"
: "${CDP_RUN_HEADER_DONE:=0}"
: "${CDP_RUN_COUNTDOWN_DONE:=0}"

cdp_run_header_channel_label() {  # [channel url]
  _hb="${1:-${CDP_RUN_CHANNEL_URL:-${CDP_INSTALLER_CHANNEL_URL:-${CDP_CHANNEL_CANON:-${CF_BASE:-}}}}}"
  _hb="${_hb%/}"
  case "$_hb" in
    *ubuntu26.installer.ctpf.network*) printf 'internal (%s)' "${_hb#https://}" ;;
    *ubuntu26.installer.cdpcdn.com*) printf 'external (%s)' "${_hb#https://}" ;;
    '') printf 'not available' ;;
    *) printf '%s' "${_hb#https://}" ;;
  esac
}

# Log of this run (root only): <dir>/<UTC>Z<suffix>.log, 0600. An open log
# of the bootstrap is kept.
cdp_run_header_open_log() {  # [suffix]
  case "${CDP_INSTALL_LOG:-}" in
    "${CDP_INSTALL_LOG_DIR}"/*) [ -f "$CDP_INSTALL_LOG" ] && return 0 ;;
  esac
  CDP_INSTALL_LOG=""
  [ "$(id -u)" -eq 0 ] || return 0
  mkdir -p "$CDP_INSTALL_LOG_DIR" 2>/dev/null || return 0
  chmod 0750 "$CDP_INSTALL_LOG_DIR" 2>/dev/null || true
  _hl="${CDP_INSTALL_LOG_DIR}/$(date -u +%Y-%m-%dT%H%M%SZ)${1:-}.log"
  _hn=0
  while [ -e "$_hl" ]; do
    _hn=$((_hn + 1))
    _hl="${CDP_INSTALL_LOG_DIR}/$(date -u +%Y-%m-%dT%H%M%SZ)${1:-}-${_hn}.log"
  done
  ( umask 077; : > "$_hl" ) 2>/dev/null || return 0
  CDP_INSTALL_LOG="$_hl"
  export CDP_INSTALL_LOG
}

cdp_run_header_render() {  # <Installer|Updater> <version>
  _hr="${1:-Installer}"
  _hv="${2:-}"
  [ -n "$_hv" ] || _hv="not available"
  _hc="$(cdp_run_header_channel_label)"
  _hh="$(hostname -f 2>/dev/null || hostname 2>/dev/null || true)"
  [ -n "$_hh" ] || _hh="not available"
  _hs="$(date '+%Y-%m-%d %H:%M:%S %Z')"
  _hf="${CDP_INSTALL_LOG:-}"
  [ -n "$_hf" ] || _hf="not available"
  # Template of Michael 22.11.2026 (4.6.100 block), text unchanged; only
  # the system name is Ubuntu 26.04.
  cat <<EOF
================================================================================
  ControlDeskPanel (CDP) ${_hr} ${_hv} for Ubuntu 26.04
================================================================================
  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  : ${_hc}
  Host     : ${_hh}
  Started  : ${_hs}
  Log file : ${_hf}

  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
}

cdp_run_header_countdown() {
  [ "${CDP_RUN_COUNTDOWN_DONE}" = "1" ] && return 0
  CDP_RUN_COUNTDOWN_DONE=1
  export CDP_RUN_COUNTDOWN_DONE
  [ "${CDP_SKIP_COUNTDOWN:-0}" = "1" ] && return 0
  trap 'echo "Cancelled. Nothing was changed."; exit 0' INT
  sleep 10
  trap - INT
  return 0
}

# Header (screen and log) plus countdown, once per run.
cdp_run_header_begin() {  # <Installer|Updater> <version> [log suffix]
  if [ "${CDP_RUN_HEADER_DONE}" != "1" ]; then
    cdp_run_header_open_log "${3:-}"
    _ht="$(cdp_run_header_render "$1" "$2")"
    printf '%s\n' "$_ht"
    if [ -n "${CDP_INSTALL_LOG:-}" ]; then
      printf '%s\n' "$_ht" >> "$CDP_INSTALL_LOG" 2>/dev/null || true
    fi
    CDP_RUN_HEADER_DONE=1
    export CDP_RUN_HEADER_DONE
  fi
  cdp_run_header_countdown
}
# <<< lib/cdp-run-header.sh

# >>> lib/channel-fetch.sh
# lib/channel-fetch.sh — ControlDeskPanel | checked downloads from the channel
# =====================================================================
# Project  : ControlDeskPanel by CTPF Certthor Platforms Ltd.
# Author   : MikeGeorg / Senior Full-Stack Developer and Team
# Version  : 4.5.79 2026-11-21 23:49:18 +0100 CET — 646: checked downloads
#            (HTTP 200, no HTML, not empty, complete, HTTPS redirects only to
#            the channel host), signed checksum manifest (gpgv of the
#            system, key of the installed version), shebang and package
#            format, channel of the installation from installation data
# Layout   : lib/channel-fetch.sh (POSIX sh). tools/build.sh copies this
#            file between the markers into one-click-installer and
#            one-click-updater; the copies are never edited by hand.
# Infos    : Every function stops cleanly through cf_stop: cause, fix and
#            retry command, exit 26. Nothing downloaded is run before all
#            checks passed. Needs: curl, gpgv, sha256sum, base64, tar, gzip.
#            Values from the bootstrap: CF_BASE, CF_HOST, CF_EDITION,
#            CF_URL_INTERN, CF_URL_EXTERN, CF_KEY_B64, CF_KEY_FPR, CF_RETRY.
# Updated  : 5.0.0 2026-11-24 22:31:35 +0100 CET — 755: no channel
#            credentials (no netrc); both channels are open

CF_ETC="${CDP_ETC:-/etc/controldeskpanel}"
CF_KEY_INSTALLED="${CF_ETC}/release-key-ubuntu26.gpg"
CF_TMP=""
CF_LOCK="${CDP_RUN_LOCK:-/run/lock/cdp-installer.lock}"

cf_log() { printf '%s\n' "$*" >&2; }
cf_read() { [ -r "$1" ] && tr -d ' \r\n' < "$1"; return 0; }

cf_stop() {  # <cause> <fix>
  cf_log "ERROR: STOP - nothing was run or changed."
  cf_log "Cause: $1"
  cf_log "Fix: $2"
  cf_log "Retry: ${CF_RETRY}"
  exit 26
}

cf_host_of() {
  printf '%s' "$1" | sed -e 's#^[a-zA-Z][a-zA-Z0-9+.-]*://##' -e 's#[:/?].*##' | tr 'A-Z' 'a-z'
}

cf_canon_of() {  # <edition>
  case "$1" in
    intern) printf '%s' "$CF_URL_INTERN" ;;
    extern) printf '%s' "$CF_URL_EXTERN" ;;
    *) printf '' ;;
  esac
}

cf_edition_of_url() {  # <url>
  _u="${1%/}"
  if [ -n "$_u" ] && [ "$_u" = "${CF_URL_INTERN%/}" ]; then printf intern
  elif [ -n "$_u" ] && [ "$_u" = "${CF_URL_EXTERN%/}" ]; then printf extern
  else printf ''; fi
}

# Channel of this installation from installation data only, never from a
# download URL, the server name, reachability or a guess:
#   /etc/controldeskpanel/edition                 (intern|extern)
#   /etc/controldeskpanel/installer-channel.default (canonical URL)
#   /etc/controldeskpanel/license-source.json     (lic01, external only)
# installer-channel.url is the download URL and no proof.
# Prints intern|extern, "none" without any installation data, or stops on
# missing or contradicting data.
cf_installation_edition() {
  _ed="$(cf_read "${CF_ETC}/edition")"
  _df="$(cf_read "${CF_ETC}/installer-channel.default")"
  _dfe="$(cf_edition_of_url "$_df")"
  _lic=""
  [ -s "${CF_ETC}/license-source.json" ] && _lic=extern
  if [ -z "$_ed" ] && [ -z "$_df" ]; then
    if [ -e "${CF_ETC}/installer-version" ] || [ -e "${CF_ETC}/installer-channel.url" ]; then
      cf_stop "the channel of this installation is not proven: ${CF_ETC}/edition and ${CF_ETC}/installer-channel.default are missing" \
        "write the edition of this installation (intern or extern) to ${CF_ETC}/edition and its channel URL to ${CF_ETC}/installer-channel.default, then retry"
    fi
    printf none
    return 0
  fi
  case "$_ed" in
    intern|extern) ;;
    *) cf_stop "the channel of this installation is not proven: ${CF_ETC}/edition is '${_ed:-missing}'" \
         "write intern or extern to ${CF_ETC}/edition (the edition this server was installed with), then retry" ;;
  esac
  if [ "$_dfe" != "$_ed" ]; then
    cf_stop "installation data contradict each other: edition=${_ed}, installer-channel.default=${_df:-missing}" \
      "set ${CF_ETC}/installer-channel.default to $(cf_canon_of "$_ed") if the edition is right, then retry"
  fi
  if [ -n "$_lic" ] && [ "$_lic" != "$_ed" ]; then
    cf_stop "installation data contradict each other: edition=${_ed}, but ${CF_ETC}/license-source.json (external licence) exists" \
      "check which edition this server was installed with and correct ${CF_ETC}/edition, then retry"
  fi
  printf '%s' "$_ed"
}

# One run at a time, taken before any download or unpacking and kept until
# the end of install.sh/update.sh (fd 9 is inherited through exec; the
# scripts take the same lock again on it, lib/common.sh cdp_run_lock).
cf_lock() {
  command -v flock >/dev/null 2>&1 || cf_stop "flock (util-linux) is missing" "apt-get install util-linux, then retry"
  mkdir -p "$(dirname "$CF_LOCK")" 2>/dev/null || true
  exec 9>>"$CF_LOCK"
  flock -n 9 || cf_stop "another CDP installer or update run is active (lock ${CF_LOCK})" \
    "wait until the running update has finished, then retry"
  CDP_RUN_LOCK_FD=9
  export CDP_RUN_LOCK_FD
}

cf_cleanup() {
  [ -n "$CF_TMP" ] && rm -rf "$CF_TMP" 2>/dev/null
  return 0
}

# cf_get <path below CF_BASE> <target file> <kind: text|script|package|manifest|signature>
# HTTPS only; a redirect is followed only to https:// on the channel host.
cf_get() {
  _p="$1"; _o="$2"; _k="$3"
  _url="${CF_BASE}/${_p}"
  _n=0
  rm -f "$_o"
  while :; do
    _hdr="${_o}.hdr"
    set -- --proto =https --tlsv1.2 -sS --max-time 600 --connect-timeout 20 -o "$_o" -D "$_hdr" \
      -w '%{http_code}\n%{redirect_url}\n%{size_download}\n'
    if [ -n "${CDP_CF_RESOLVE:-}" ]; then
      # Build gate only: name -> 127.0.0.1 of the test server (curl --resolve).
      case "$CDP_CF_RESOLVE" in
        *[!A-Za-z0-9.:-]*) cf_stop "invalid CDP_CF_RESOLVE" "unset CDP_CF_RESOLVE" ;;
      esac
      set -- "$@" --resolve "$CDP_CF_RESOLVE"
    fi
    _rc=0
    _w="$(curl "$@" "$_url" 2>"${_o}.err")" || _rc=$?
    _code="$(printf '%s\n' "$_w" | sed -n 1p)"
    _loc="$(printf '%s\n' "$_w" | sed -n 2p)"
    _size="$(printf '%s\n' "$_w" | sed -n 3p)"
    if [ "$_rc" -ne 0 ]; then
      _e="$(head -c 300 "${_o}.err" 2>/dev/null | tr '\n' ' ')"
      rm -f "$_o" "$_hdr" "${_o}.err"
      cf_stop "download of ${_url} aborted (curl exit ${_rc}: ${_e})" \
        "check the connection to ${CF_HOST} (HTTPS); an aborted or cut transfer is never used"
    fi
    rm -f "${_o}.err"
    case "$_code" in
      301|302|303|307|308)
        _n=$((_n + 1))
        case "$_loc" in
          https://*) ;;
          *) rm -f "$_o" "$_hdr"
             cf_stop "${_url} redirects to '${_loc}' (not HTTPS)" "the channel must answer on HTTPS only; inform the channel operator" ;;
        esac
        if [ "$(cf_host_of "$_loc")" != "$CF_HOST" ]; then
          rm -f "$_o" "$_hdr"
          cf_stop "${_url} redirects to another host ($(cf_host_of "$_loc"))" \
            "downloads come only from the channel host ${CF_HOST}; inform the channel operator"
        fi
        [ "$_n" -le 3 ] || { rm -f "$_o" "$_hdr"; cf_stop "too many redirects for ${_url}" "inform the channel operator"; }
        _url="$_loc"
        continue ;;
      200) ;;
      *) rm -f "$_o" "$_hdr"
         cf_stop "${_url} answered HTTP ${_code:-none} instead of 200" \
           "the file is missing in the channel or the channel is not reachable; check ${CF_BASE}/ and retry later" ;;
    esac
    break
  done
  if [ ! -s "$_o" ] || [ "${_size:-0}" = "0" ]; then
    rm -f "$_o" "$_hdr"
    cf_stop "${_url} is empty (HTTP 200 without content)" "the channel delivers an empty file; inform the channel operator"
  fi
  _len="$(tr -d '\r' < "$_hdr" | sed -n 's/^[Cc]ontent-[Ll]ength:[[:space:]]*//p' | tail -n 1)"
  if [ -n "$_len" ] && [ "$_len" != "$(wc -c < "$_o" | tr -d ' ')" ]; then
    rm -f "$_o" "$_hdr"
    cf_stop "${_url} is incomplete (${_size} of ${_len} bytes)" "the transfer was cut; retry"
  fi
  if tr -d '\r' < "$_hdr" | grep -qi '^content-type:[[:space:]]*text/html' \
     || head -c 512 "$_o" | tr -d '\000' | tr 'A-Z' 'a-z' | sed 's/^[[:space:]]*//' | head -n 3 \
        | grep -Eq '^(<!doctype html|<html|<head|<body)'; then
    rm -f "$_o" "$_hdr"
    cf_stop "${_url} delivered an HTML page instead of the file" \
      "the channel shows an error or login page; check ${CF_BASE}/ and retry later"
  fi
  rm -f "$_hdr"
  case "$_k" in
    script)
      case "$(head -n 1 "$_o")" in
        '#!/bin/sh'|'#!/usr/bin/env bash'|'#!/bin/bash') ;;
        *) rm -f "$_o"; cf_stop "${_url} is no shell script (first line: $(head -c 40 "$_o" 2>/dev/null))" "inform the channel operator" ;;
      esac ;;
    package)
      if [ "$(od -An -tx1 -N2 "$_o" | tr -d ' \n')" != "1f8b" ] || ! gzip -t "$_o" 2>/dev/null \
         || ! tar -tzf "$_o" >/dev/null 2>&1; then
        rm -f "$_o"; cf_stop "${_url} is no complete tar.gz package" "the package is damaged or cut; retry"
      fi ;;
    signature)
      grep -q '^-----BEGIN PGP SIGNATURE-----' "$_o" \
        || { rm -f "$_o"; cf_stop "${_url} is no OpenPGP signature" "inform the channel operator"; } ;;
    manifest)
      if grep -Evq '^[0-9a-f]{64}  [A-Za-z0-9._/-]+$' "$_o"; then
        rm -f "$_o"; cf_stop "${_url} is no checksum manifest" "inform the channel operator"
      fi ;;
    text) ;;
  esac
  return 0
}

# Release key: the key of the installed version wins; the key carried by
# this bootstrap must be the same (a key change is never taken silently).
cf_keyring() {  # <target file>
  printf '%s' "$CF_KEY_B64" | base64 -d > "$1" 2>/dev/null || cf_stop "release key of this bootstrap is not readable" "inform the channel operator"
  if [ -s "$CF_KEY_INSTALLED" ] && ! cmp -s "$CF_KEY_INSTALLED" "$1"; then
    cf_stop "the release key of this bootstrap differs from the key of the installed version (${CF_KEY_INSTALLED})" \
      "this download is not from the release signer of your installation; do not continue and inform the channel operator"
  fi
  [ -s "$CF_KEY_INSTALLED" ] && cp "$CF_KEY_INSTALLED" "$1"
  return 0
}

# cf_verify_manifest <manifest> <signature> <keyring>: gpgv of the system,
# signed by the expected key (fingerprint), good signature only.
cf_verify_manifest() {
  command -v gpgv >/dev/null 2>&1 || cf_stop "gpgv (GnuPG) is missing - the signature cannot be checked" "apt-get install gpgv, then retry"
  _st="$(gpgv --status-fd 1 --keyring "$3" "$2" "$1" 2>/dev/null)" || \
    cf_stop "the signature of the checksum manifest ${1##*/} is wrong or missing" \
      "the download is not the signed release; do not continue, retry later or inform the channel operator"
  printf '%s\n' "$_st" | grep -q "^\[GNUPG:\] VALIDSIG ${CF_KEY_FPR} " \
    || cf_stop "the manifest is not signed by the release key ${CF_KEY_FPR}" "inform the channel operator"
  return 0
}

# cf_check_sum <manifest> <name in the manifest> <file>
cf_check_sum() {
  _want="$(awk -v n="$2" '$2 == n {print $1}' "$1" | head -n 1)"
  [ -n "$_want" ] || cf_stop "${2} is not listed in the signed manifest" "inform the channel operator"
  _have="$(sha256sum "$3" | cut -d' ' -f1)"
  [ "$_want" = "$_have" ] || cf_stop "SHA-256 of ${2} does not match the signed manifest (expected ${_want}, got ${_have})" \
    "the download is damaged or changed; retry"
  return 0
}

# cf_fetch_release <version> <workdir>: manifest, signature, package; all
# checked. Sets CF_PKG.
cf_fetch_release() {
  _v="$1"; _wd="$2"
  cf_get "releases/cdp-installer-${_v}.SHA256SUMS" "${_wd}/SHA256SUMS" manifest
  cf_get "releases/cdp-installer-${_v}.SHA256SUMS.asc" "${_wd}/SHA256SUMS.asc" signature
  cf_keyring "${_wd}/release-key.gpg"
  cf_verify_manifest "${_wd}/SHA256SUMS" "${_wd}/SHA256SUMS.asc" "${_wd}/release-key.gpg"
  cf_get "releases/cdp-installer-${_v}.tgz" "${_wd}/cdp-installer-${_v}.tgz" package
  cf_check_sum "${_wd}/SHA256SUMS" "releases/cdp-installer-${_v}.tgz" "${_wd}/cdp-installer-${_v}.tgz"
  if tar -tzf "${_wd}/cdp-installer-${_v}.tgz" | grep -Eq '^/|^~|(^|/)\.\.(/|$)'; then
    cf_stop "unsafe archive member in the package" "inform the channel operator"
  fi
  CF_PKG="${_wd}/cdp-installer-${_v}.tgz"
  return 0
}
# <<< lib/channel-fetch.sh

CF_EDITION="$KANAL_EDITION"
CF_URL_INTERN="$KANAL_URL_INTERN"
CF_URL_EXTERN="$KANAL_URL_EXTERN"
CF_KEY_FPR="$KANAL_KEY_FPR"
CF_KEY_B64="$KANAL_KEY_B64"
CF_RETRY="curl -fsSL ${KANAL_BASIS}/one-click-updater | sh"

# Only the own channel host: a base from the environment is used when it is
# on the same host (test copies of the channel); any other host is ignored.
CF_BASE="${CDP_INSTALLER_BASE:-$KANAL_BASIS}"
CF_BASE="${CF_BASE%/}"
CF_BASE_IGNORED=""
if [ "$(cf_host_of "$CF_BASE")" != "$(cf_host_of "$KANAL_BASIS")" ]; then
  CF_BASE_IGNORED="$CF_BASE"   # 755: reported after the header
  CF_BASE="$KANAL_BASIS"
fi
case "$CF_BASE" in
  https://*) ;;
  *) cf_stop "the channel must be https:// (${CF_BASE})" "use ${KANAL_BASIS}" ;;
esac
if printf '%s' "$CF_BASE" | grep -Eq '[`$"'"'"'|(){};&<> ]'; then
  cf_stop "invalid channel address" "use ${KANAL_BASIS}"
fi
CF_HOST="$(cf_host_of "$CF_BASE")"

# 755: the mandatory header is the first output of the run (before any
# check, question or download message). The version is read silently;
# the checked download below stops with cause if it is not readable.
# (own variable, the arguments of this run stay in "$@" for install.sh)
HDR_RESOLVE=""
case "${CDP_CF_RESOLVE:-}" in
  ''|*[!A-Za-z0-9.:-]*) ;;
  *) HDR_RESOLVE="$CDP_CF_RESOLVE" ;;
esac
HDR_VER="$(curl --proto =https --tlsv1.2 -fsS --max-time 20 --connect-timeout 10 \
  ${HDR_RESOLVE:+--resolve "$HDR_RESOLVE"} \
  "${CF_BASE}/VERSION-${OS_KEY_WANT}" 2>/dev/null | tr -d '\r\n ' || true)"
case "$HDR_VER" in
  [0-9]*.[0-9]*.[0-9]*-"$OS_KEY_WANT") HDR_VER="${HDR_VER%-"$OS_KEY_WANT"}" ;;
  *) HDR_VER="" ;;
esac
# 824: the header names the updater that runs (this file); the channel
# version is printed below ("Version in the channel").
[ -z "$KANAL_BOOT_VERSION" ] || HDR_VER="$KANAL_BOOT_VERSION"
CDP_RUN_CHANNEL_URL="$CF_BASE"
if [ "$CDP_BOOT_MODE" = "update" ]; then
  cdp_run_header_begin Updater "$HDR_VER" "-update"
else
  cdp_run_header_begin Installer "$HDR_VER" ""
fi
unset HDR_VER HDR_RESOLVE
if [ -n "$CF_BASE_IGNORED" ]; then
  cf_log "Channel ${CF_BASE_IGNORED} is not this channel - using ${KANAL_BASIS}"
fi
trap 'cf_cleanup' EXIT INT TERM HUP

[ "$(id -u)" -eq 0 ] || cf_stop "not run as root" "run as root: ${CF_RETRY}"
[ -n "$CF_KEY_FPR" ] && [ -n "$CF_KEY_B64" ] || cf_stop "this bootstrap carries no release key" "inform the channel operator"
cf_lock

. /etc/os-release 2>/dev/null || true
[ "${ID:-}" = "ubuntu" ] && [ "${VERSION_ID:-}" = "26.04" ] \
  || cf_stop "this channel is for Ubuntu 26.04 only (found ${ID:-?} ${VERSION_ID:-?})" "use the channel of your system"
OS_KEY="$OS_KEY_WANT"

# Channel of an existing installation from its installation data. A server
# of the other edition is never moved to this channel.
INST_ED="$(cf_installation_edition)"
if [ "$CDP_BOOT_MODE" = "update" ] && [ "$INST_ED" = "none" ]; then
  cf_stop "no CDP installation found on this server (${CF_ETC})" \
    "install first: curl -fsSL ${KANAL_BASIS}/one-click-installer | sh"
fi
if [ "$INST_ED" != "none" ] && [ "$INST_ED" != "$KANAL_EDITION" ]; then
  cf_stop "this server is a CDP ${INST_ED} installation (installation data), this is the ${KANAL_EDITION} channel - no channel switch" \
    "use the channel of this installation: curl -fsSL $(cf_canon_of "$INST_ED")/one-click-updater | sh"
fi

umask 077
CF_TMP="$(mktemp -d "${TMPDIR:-/tmp}/cdp-installer.XXXXXX")" \
  || cf_stop "no temporary directory in ${TMPDIR:-/tmp}" "free space or fix TMPDIR, then retry"

cf_get "RELEASED-${OS_KEY}" "${CF_TMP}/RELEASED" text
[ "$(tr -d '\r\n ' < "${CF_TMP}/RELEASED")" = "1" ] \
  || cf_stop "no release for ${OS_KEY} in this channel (RELEASED-${OS_KEY})" "retry later"
cf_get "VERSION-${OS_KEY}" "${CF_TMP}/VERSION" text
VERSION="$(tr -d '\r\n ' < "${CF_TMP}/VERSION")"
case "$VERSION" in
  *[!0-9a-z.-]*) cf_stop "implausible version in the channel: '${VERSION}'" "retry later" ;;
  [0-9]*.[0-9]*.[0-9]*-"$OS_KEY") ;;
  *) cf_stop "implausible version in the channel: '${VERSION}'" "retry later" ;;
esac
echo "Version in the channel: ${VERSION}"
# 781: never step back. A channel version older than the installed one
# stops the update before any download; the same version may run again.
CF_INST_VER="$(tr -d '\r\n ' < "${CF_ETC}/installer-version" 2>/dev/null || true)"
CF_INST_VER="${CF_INST_VER%-"$OS_KEY"}"
CF_CHAN_VER="${VERSION%-"$OS_KEY"}"
case "$CF_INST_VER" in
  *[!0-9.]*|'') ;;
  [0-9]*.[0-9]*.[0-9]*)
    if [ "$CDP_BOOT_MODE" = "update" ] && [ "$CF_INST_VER" != "$CF_CHAN_VER" ] \
      && [ "$(printf '%s\n%s\n' "$CF_CHAN_VER" "$CF_INST_VER" | sort -V | tail -n 1)" = "$CF_INST_VER" ]; then
      # 824: no error - a clear notice on screen, in the panel and in the
      # run log; the Cause line stays (cdp-system-waechter, 814)
      for _l in \
        "Channel version ${CF_CHAN_VER} is older than installed ${CF_INST_VER} - no update" \
        "Cause: installed version ${CF_INST_VER} is newer than the channel version ${CF_CHAN_VER} - no downgrade" \
        "Nothing was run or changed. Run the update again when the channel offers a newer version."; do
        printf '%s\n' "$_l"
        [ -z "${CDP_INSTALL_LOG:-}" ] || printf '%s\n' "$_l" >> "$CDP_INSTALL_LOG" 2>/dev/null || true
      done
      exit 26
    fi
    ;;
esac

cf_fetch_release "$VERSION" "$CF_TMP"
echo "Signed manifest, SHA-256 and package format: OK"

# Own directory per run: a fixed name was removed by a second run while
# the first one was still working in it.
KEEP="$(mktemp -d "${TMPDIR:-/tmp}/cdp-installer-${VERSION}.XXXXXX")" \
  || cf_stop "no temporary directory in ${TMPDIR:-/tmp}" "free space or fix TMPDIR, then retry"
# 764: a stop before the start of update.sh also removes the unpacked package
trap 'cf_cleanup; rm -rf "$KEEP"' EXIT INT TERM HUP
tar -xzf "$CF_PKG" -C "$KEEP" \
  || cf_stop "the package could not be unpacked to ${KEEP}" "free space in ${TMPDIR:-/tmp}, then retry"
# 788: exactly the updater of the package top folder cdp-installer-*/, never
# a script further down and never a guess between two of them.
inner="$(find "$KEEP" -mindepth 2 -maxdepth 2 -path "${KEEP}/cdp-installer-*/update.sh" -type f)"
[ -n "$inner" ] || cf_stop "update.sh missing in the package" "inform the channel operator"
[ "$(printf '%s\n' "$inner" | wc -l)" -eq 1 ] \
  || cf_stop "the package carries more than one cdp-installer-*/update.sh" "inform the channel operator"
case "$(head -n 1 "$inner")" in
  '#!/usr/bin/env bash'|'#!/bin/bash') ;;
  *) cf_stop "update.sh in the package is no bash script" "inform the channel operator" ;;
esac
( cd "$(dirname "$inner")" && sha256sum -c --quiet MANIFEST.sha256 >/dev/null 2>&1 ) \
  || cf_stop "the package content does not match its MANIFEST.sha256" "retry; inform the channel operator if it repeats"
RUN="$(dirname "$inner")"

# The channel of this run; install.sh/update.sh store it (lib/common.sh).
CDP_INSTALLER_CHANNEL_URL="$KANAL_BASIS"
export CDP_INSTALLER_CHANNEL_URL

cf_cleanup
trap - EXIT INT TERM HUP
cd "$RUN" || cf_stop "the package directory ${RUN} is not usable" "retry"
chmod +x ./install.sh ./update.sh 2>/dev/null || true
echo "Package ready in ${RUN}"
# 641: never a question, with or without terminal (stdin empty).
exec ./update.sh --one-click --unattended "$@" </dev/null
