#!/bin/sh
# ONE PASTE ON A LINUX SERVER (1816): THE PENTAL GATEWAY, OR SUPABASE'S STACK
# WITH THE PENTAL OVERLAY, AND DOCKER PUT IN FIRST WHEN IT IS NOT THERE.
#
#   curl -fsSL https://pental.io/downloads/pental-server.sh | sh -s -- gateway db.yourfirm.com https://yourfirm.pental.io
#   curl -fsSL https://pental.io/downloads/pental-server.sh | sh -s -- kit db.yourfirm.com https://yourfirm.pental.io
#
# [stated] Arian: "remember it needs to be seamless", and "again aws just an
# examples others probably the same". A server's paste ran only once Docker had
# been installed on it by hand (with its Compose plugin new enough), unzip
# too, and its user let into Docker. This puts in what is missing (Docker and
# Compose from Docker's own install script, or the distribution's packages on
# Amazon Linux and Alpine; bash; openssl for the kit), fetches the
# newest gateway or kit into a folder here (over an earlier one, keeping its
# .env and its data), makes its secrets, starts it, and prints the lines the
# pental.io wizard reads. Pasted again, it updates in place.
#
# It asks nothing. sudo may ask for your password once, to install.
set -eu

say() { printf '%s\n' "$*"; }
fail() { printf '%s\n' "$*" >&2; exit 1; }
# A step that failed, with the end of what it said and where the rest is.
fail_log() {
  if [ -s "$LOG" ]; then tail -n 15 "$LOG" >&2; printf 'All of it: %s\n' "$LOG" >&2; fi
  fail "$1"
}

# Is version $1 older than version $2? Numbers between dots, compared as numbers.
ver_lt() {
  awk -v a="$1" -v b="$2" 'BEGIN {
    n = split(a, x, "."); m = split(b, y, "."); k = n > m ? n : m
    for (i = 1; i <= k; i++) { p = x[i] + 0; q = y[i] + 0; if (p < q) exit 0; if (p > q) exit 1 }
    exit 1 }'
}

fetch() {
  if command -v curl >/dev/null 2>&1; then curl -fsSL --retry 3 -o "$2" "$1"
  else wget -q -O "$2" "$1"; fi
}

pkg_install() {
  case "$PM" in
    apt-get)
      $SUDO env DEBIAN_FRONTEND=noninteractive apt-get update -qq </dev/null >>"$LOG" 2>&1 || true
      $SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq "$@" </dev/null >>"$LOG" 2>&1 ;;
    dnf) $SUDO dnf install -y -q "$@" </dev/null >>"$LOG" 2>&1 ;;
    yum) $SUDO yum install -y -q "$@" </dev/null >>"$LOG" 2>&1 ;;
    zypper) $SUDO zypper --non-interactive --quiet install "$@" </dev/null >>"$LOG" 2>&1 ;;
    apk) $SUDO apk add --no-cache "$@" </dev/null >>"$LOG" 2>&1 ;;
    *) return 1 ;;
  esac
}

# need <command> <package>: put in when it is not there.
need() {
  command -v "$1" >/dev/null 2>&1 && return 0
  [ -n "$PM" ] || fail "This server has no $1, and no package manager this knows (apt, dnf, yum, zypper or apk) to put it in. Install $2, then run this again."
  say "→ putting in $2"
  pkg_install "$2" || fail_log "Could not install $2 on this server. Install it, then run this again."
  command -v "$1" >/dev/null 2>&1 || fail_log "$2 was installed but $1 is still not found. Install it, then run this again."
}

compose_version() { $SUDO docker compose version --short 2>/dev/null | sed 's/^v//' | head -n 1; }

start_docker() {
  $SUDO docker info >/dev/null 2>&1 && return 0
  if command -v systemctl >/dev/null 2>&1; then
    $SUDO systemctl enable --now docker </dev/null >>"$LOG" 2>&1 || true
  elif command -v rc-service >/dev/null 2>&1; then
    $SUDO rc-update add docker default </dev/null >>"$LOG" 2>&1 || true
    $SUDO rc-service docker start </dev/null >>"$LOG" 2>&1 || true
  elif command -v service >/dev/null 2>&1; then
    $SUDO service docker start </dev/null >>"$LOG" 2>&1 || true
  fi
  i=0
  while [ "$i" -lt 30 ]; do
    $SUDO docker info >/dev/null 2>&1 && return 0
    i=$((i + 1)); sleep 1
  done
  fail_log "Docker is installed but does not start. On most servers: sudo systemctl start docker. Then run this again."
}

# ── the name, leading to this server (1817) ─────────────────────────────────
# [stated] Arian: "make sure its as seamless as possible and those kinds of
# mistakes dont happen, in all of them", after a record typed with its whole
# name at GoDaddy (which adds the domain itself) left a setup waiting on it.
# This server's public address, the A record to add as the domain's DNS
# provider wants it typed, and the name watched until it leads here, with
# what is wrong said when it does not. Asked of public DNS over
# DNS-over-HTTPS (Cloudflare's resolver, then Google's), as the pental.io
# wizard asks it; a lookup that fails says nothing rather than guess.
bare() { printf '%s' "$1" | tr 'A-Z' 'a-z' | sed 's/\.$//'; }

doh() {
  for doh_u in https://cloudflare-dns.com/dns-query https://dns.google/resolve; do
    doh_out="$(curl -fsS --max-time 5 -H 'accept: application/dns-json' "$doh_u?name=$1&type=$2" 2>/dev/null)" || continue
    case "$doh_out" in *'"Status"'*) printf '%s' "$doh_out" | tr -d '\n\r'; return 0 ;; esac
  done
  return 1
}
doh_status() { printf '%s' "$1" | sed -n 's/.*"Status"[[:space:]]*:[[:space:]]*\([0-9]*\).*/\1/p' | head -n 1; }
# The records in one section of an answer, a line each: name TAB type TAB data.
doh_records() {
  printf '%s' "$1" | sed -n "s/.*\"$2\"[[:space:]]*:[[:space:]]*\[\([^]]*\)\].*/\1/p" \
    | awk '{ gsub(/[}],[[:space:]]*[{]/, "}\n{"); print }' \
    | while IFS= read -r rec; do
        n="$(printf '%s' "$rec" | sed -n 's/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')"
        t="$(printf '%s' "$rec" | sed -n 's/.*"type"[[:space:]]*:[[:space:]]*\([0-9]*\).*/\1/p')"
        d="$(printf '%s' "$rec" | sed -n 's/.*"data"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')"
        if [ -n "$t" ]; then printf '%s\t%s\t%s\n' "$(bare "$n")" "$t" "$(bare "$d")"; fi
      done
}
# A "zone" of two labels under which domains have three (co.uk) is a suffix
# nobody owns.
suffix_only() {
  case "$1" in *.*) ;; *) return 0 ;; esac
  for so_s in co.uk org.uk me.uk ltd.uk plc.uk ac.uk gov.uk net.uk com.au net.au org.au co.nz org.nz co.za com.br co.jp co.in com.sg com.hk co.il com.mx co.kr com.tr com.cn; do
    [ "$1" = "$so_s" ] && return 0
  done
  return 1
}
# The zone that holds a name: the owner of the SOA record a lookup answers
# with (a name that is itself a CNAME answers with the SOA of where it leads,
# so its parent is asked instead).
dns_zone() {
  dz_q="$(bare "$1")"; dz_i=0
  while [ "$dz_i" -lt 2 ]; do
    case "$dz_q" in *.*) ;; *) return 1 ;; esac
    dz_j="$(doh "$dz_q" SOA)" || return 1
    dz_s="$(doh_status "$dz_j")"
    [ "$dz_s" = 0 ] || [ "$dz_s" = 3 ] || return 1
    if doh_records "$dz_j" Answer | awk -F'\t' -v q="$dz_q" '$1 == q && $2 == 5 { f = 1 } END { exit !f }'; then
      dz_q="${dz_q#*.}"; dz_i=$((dz_i + 1)); continue
    fi
    dz_z="$( { doh_records "$dz_j" Answer; doh_records "$dz_j" Authority; } | awk -F'\t' '$2 == 6 { print $1; exit }')"
    [ -n "$dz_z" ] || return 1
    suffix_only "$dz_z" && return 1
    printf '%s' "$dz_z"
    return 0
  done
  return 1
}
# Who runs a zone's DNS, from its nameservers (the wizard's list).
dns_provider() {
  dp_j="$(doh "$1" NS)" || return 0
  for dp_h in $(doh_records "$dp_j" Answer | awk -F'\t' '$2 == 2 { print $3 }'); do
    case "$dp_h" in
      *.awsdns-*) echo "Amazon Route 53"; return 0 ;;
      *.ns.cloudflare.com) echo "Cloudflare"; return 0 ;;
      *.domaincontrol.com) echo "GoDaddy"; return 0 ;;
      *.azure-dns.com|*.azure-dns.net|*.azure-dns.org|*.azure-dns.info) echo "Azure DNS"; return 0 ;;
      *.googledomains.com) echo "Google Cloud DNS"; return 0 ;;
      *.registrar-servers.com) echo "Namecheap"; return 0 ;;
      *.ui-dns.com|*.ui-dns.org|*.ui-dns.de|*.ui-dns.biz) echo "IONOS"; return 0 ;;
      *.123-reg.co.uk) echo "123 Reg"; return 0 ;;
      *.digitalocean.com) echo "DigitalOcean"; return 0 ;;
      *.ovh.net|*.ovh.ca) echo "OVHcloud"; return 0 ;;
      *.gandi.net) echo "Gandi"; return 0 ;;
      *.hetzner.com|*.hetzner.de) echo "Hetzner"; return 0 ;;
      *.linode.com) echo "Akamai (Linode)"; return 0 ;;
      *.dnsimple.com) echo "DNSimple"; return 0 ;;
      *.nsone.net) echo "NS1"; return 0 ;;
      *.wixdns.net) echo "Wix"; return 0 ;;
      *.porkbun.com) echo "Porkbun"; return 0 ;;
      *.worldnic.com) echo "Network Solutions"; return 0 ;;
      *.vercel-dns.com) echo "Vercel"; return 0 ;;
      *.akam.net) echo "Akamai"; return 0 ;;
      *.ultradns.com|*.ultradns.net|*.ultradns.org|*.ultradns.biz|*.ultradns.info) echo "UltraDNS"; return 0 ;;
      *.dnsmadeeasy.com) echo "DNS Made Easy"; return 0 ;;
    esac
  done
  return 0
}
dns_relative() {
  dr_n="$(bare "$1")"; dr_z="$(bare "$2")"
  if [ -z "$dr_z" ]; then printf '%s' "$dr_n"
  elif [ "$dr_n" = "$dr_z" ]; then printf '@'
  else case "$dr_n" in *".$dr_z") printf '%s' "${dr_n%".$dr_z"}" ;; *) printf '%s' "$dr_n" ;; esac; fi
}
adds_zone() {
  case "$1" in
    Cloudflare|GoDaddy|Namecheap|"Amazon Route 53"|"Azure DNS"|"Google Cloud DNS"|IONOS|"123 Reg"|DigitalOcean|OVHcloud|Gandi|Hetzner|"Akamai (Linode)"|DNSimple|Wix|Porkbun|"Network Solutions"|Vercel|"DNS Made Easy") return 0 ;;
  esac
  return 1
}
DZ=""; DP=""
dns_where() {
  DZ="$(dns_zone "$1" || true)"
  DP=""
  if [ -n "$DZ" ]; then DP="$(dns_provider "$DZ")"; fi
  return 0
}
dns_place() {
  if [ -n "$DP" ]; then printf 'at %s, where the DNS for %s is managed' "$DP" "$DZ"
  elif [ -n "$DZ" ]; then printf 'where the DNS for %s is managed' "$DZ"
  else printf 'where the DNS for your domain is managed (Cloudflare, GoDaddy, your IT provider...)'; fi
}
# This server's address on the internet, as two services that only say it
# see it; nothing when neither answers.
public_ip() {
  for pi_u in https://checkip.amazonaws.com https://api.ipify.org; do
    pi_ip="$(curl -fsS --max-time 5 "$pi_u" 2>/dev/null | tr -d ' \r\n')" || continue
    case "$pi_ip" in ""|*[!0-9.]*) continue ;; *.*.*.*) printf '%s' "$pi_ip"; return 0 ;; esac
  done
  return 1
}
# How the name stands: ok (it leads here), unknown (DNS could not be asked),
# none (nothing there yet), doubled (the provider put the domain on its name
# twice), address <ip> (another address; at Cloudflare, a proxied record),
# cname <target> (a CNAME leading elsewhere).
a_check() {
  ac_j="$(doh "$HOST" A)" || { echo unknown; return 0; }
  ac_s="$(doh_status "$ac_j")"
  if [ "$ac_s" != 0 ] && [ "$ac_s" != 3 ]; then echo unknown; return 0; fi
  ac_a="$(doh_records "$ac_j" Answer | awk -F'\t' '$2 == 1 { print $3 }')"
  ac_c="$(doh_records "$ac_j" Answer | awk -F'\t' -v n="$(bare "$HOST")" '$1 == n && $2 == 5 { print $3; exit }')"
  # Leading here, directly or through a CNAME: in place.
  if [ -n "$ac_a" ] && { [ -z "$IP" ] || printf '%s\n' "$ac_a" | grep -qx "$IP"; }; then echo ok; return 0; fi
  # A CNAME leading elsewhere: its value cannot be this server's address, so
  # the record itself is replaced.
  if [ -n "$ac_c" ]; then echo "cname $ac_c"; return 0; fi
  if [ -n "$ac_a" ]; then echo "address $(printf '%s\n' "$ac_a" | head -n 1)"; return 0; fi
  if [ -n "$DZ" ] && ac_j="$(doh "$HOST.$DZ" A)" && [ -n "$(doh_records "$ac_j" Answer | awk -F'\t' '$2 == 1 || $2 == 5 { print; exit }')" ]; then echo doubled; return 0; fi
  echo none
}
# This server's address, or what to put there when it could not be told.
ip_text() { if [ -n "$IP" ]; then printf '%s' "$IP"; else printf '%s' "this server's public IP address"; fi; }
a_says() {
  as_rel="$(dns_relative "$HOST" "$DZ")"
  case "$1" in
    ok) say "→ $HOST leads to this server${IP:+ ($IP)}" ;;
    doubled) say "  The record is at $HOST.$DZ: ${DP:-your DNS provider} added $DZ to its Name a second time. Change its Name to $as_rel (just that)." ;;
    address\ *)
      if [ "$DP" = Cloudflare ]; then say "  $HOST answers with Cloudflare's own addresses: its record is proxied (the orange cloud). Make it DNS only (the grey cloud)."
      else say "  $HOST leads to ${1#address }, not this server${IP:+ ($IP)}: change the record's value to $(ip_text)."; fi ;;
    cname\ *) say "  $HOST is a CNAME to ${1#cname }, which does not lead here: replace it with the A record above." ;;
  esac
  return 0
}
show_a_record() {
  say ""
  printf '%s\n' "For https://$HOST, add this record $(dns_place), so the name leads to this server:" | fold -s -w 76 | sed 's/^/  /; s/ *$//'
  say ""
  say "    Type   A"
  if [ -n "$DZ" ]; then say "    Name   $(dns_relative "$HOST" "$DZ")"; else say "    Name   $HOST"; fi
  say "    Value  $(ip_text)"
  if [ "$DP" = Cloudflare ]; then say "    Proxy  DNS only (the grey cloud)"; fi
  say ""
  if [ -n "$DZ" ] && [ -n "$DP" ] && adds_zone "$DP"; then
    say "  Type the Name just as it is here: $DP adds $DZ to it itself."
  elif [ -n "$DZ" ]; then
    say "  Most providers add $DZ to the Name themselves. One that wants the whole"
    say "  name takes $HOST"
  else
    say "  (A provider that adds your domain to every name itself wants the Name without"
    say "  the domain on the end. At Cloudflare, make it DNS only: the grey cloud.)"
  fi
  say ""
  return 0
}

# The stack answering over https, with its certificate; the gateway's
# publishable key, asked of it with the setup token on curl's input.
answers() { curl -fsS -o /dev/null --max-time 10 -H "apikey: $ANON" "$PROBE" 2>/dev/null; }
gateway_key() { printf 'Authorization: Bearer %s\n' "$TOKEN" | curl -fsS --max-time 10 -H @- "https://$HOST/pental/v1/keys" 2>/dev/null | sed -n 's/.*"publishable_key":"\([^"]*\)".*/\1/p' || true; }

main() {
  KIND="${1:-}"; HOST="${2:-}"; PORTAL="${3:-}"
  SITE="${PENTAL_SITE:-https://pental.io}"
  case "$KIND" in
    gateway) WHAT="Pental gateway"; FILE="pental-gateway-latest.tar.gz"; DIR="pental-gateway/deploy/compose"; PAGE="PostgreSQL in your cloud" ;;
    kit) WHAT="Supabase stack with the Pental overlay"; FILE="pental-self-hosted-kit-latest.tar.gz"; DIR="pental-self-hosted-kit"; PAGE="Self-hosted Supabase" ;;
    *) fail "Usage: curl -fsSL $SITE/downloads/pental-server.sh | sh -s -- gateway|kit <the server's DNS name> <your portal address>" ;;
  esac
  HOST="$(printf '%s' "$HOST" | tr 'A-Z' 'a-z' | sed -e 's#^https://##' -e 's#^http://##' -e 's#/.*$##')"
  case "$HOST" in
    ""|*[!a-z0-9.-]*|.*|*.|*..*) fail "The server's name must be a DNS name, such as db.yourfirm.com (it is: $HOST)" ;;
    *.*) ;;
    *) fail "The server's name must be a full DNS name, such as db.yourfirm.com (it is: $HOST)" ;;
  esac
  PORTAL="${PORTAL%/}"
  case "$PORTAL" in https://*) ;; *) fail "Your portal address must start with https://, such as https://yourfirm.pental.io" ;; esac
  case "$PORTAL" in *[!A-Za-z0-9.:/_-]*) fail "The portal address has characters an address does not: $PORTAL" ;; esac
  [ "$(uname -s)" = Linux ] || fail "This is for a Linux server (this is $(uname -s)). Sign in to the server with ssh and paste it there."

  WORK="$(mktemp -d "${TMPDIR:-/tmp}/pental-server.XXXXXX")"
  LOG="$WORK/log"
  : >"$LOG"

  if [ "$(id -u)" = 0 ]; then SUDO=""
  elif command -v sudo >/dev/null 2>&1; then
    SUDO="sudo"
    # A password, when sudo wants one, is asked for here, once and said why:
    # not in the middle of an install whose output goes to the log (and with
    # no terminal to ask on, said so, rather than as a failed install).
    if ! sudo -n true 2>/dev/null; then
      say "→ sudo asks for your password (once), to put in what is missing and run Docker"
      sudo -v || fail "sudo did not let $(id -un) in, so nothing was put in. Run this as root, or as a user who may use sudo (signed in with ssh, so sudo has a terminal to ask on)."
    fi
  else fail "This puts software on the server: run it as root, or as a user who may use sudo."; fi

  PM=""
  for p in apt-get dnf yum zypper apk; do
    if command -v "$p" >/dev/null 2>&1; then PM="$p"; break; fi
  done
  OSR="${PENTAL_OS_RELEASE:-/etc/os-release}"
  # shellcheck source=/dev/null
  DISTRO="$( (. "$OSR" && printf '%s' "${ID:-}") 2>/dev/null || true)"
  # shellcheck source=/dev/null
  PRETTY="$( (. "$OSR" && printf '%s' "${PRETTY_NAME:-}") 2>/dev/null || true)"
  [ -n "$PRETTY" ] || PRETTY="this Linux"

  # The kit is Supabase's whole stack, which wants 4 GB of memory: on much
  # less its services fall over one by one. Said now, and it carries on.
  if [ "$KIND" = kit ]; then
    MEM="$(awk '/^MemTotal:/ { print int($2 / 1024) }' "${PENTAL_MEMINFO:-/proc/meminfo}" 2>/dev/null || true)"
    case "$MEM" in ""|*[!0-9]*) ;; *)
      if [ "$MEM" -lt 3500 ]; then
        say "→ note: this server has $(awk -v m="$MEM" 'BEGIN { printf "%.1f", m / 1024 }') GB of memory, and Supabase's stack wants 4 GB. It may not stay up on less: if it does not, a larger server is the fix."
      fi ;;
    esac
  fi

  need curl curl
  need tar tar
  need gzip gzip
  need bash bash
  if [ "$KIND" = kit ]; then need openssl openssl; fi

  # Docker, from Docker's own script where it has one (Ubuntu, Debian,
  # Raspberry Pi OS, CentOS, RHEL, Fedora); Docker's RHEL packages on Rocky,
  # AlmaLinux and Oracle Linux; Amazon Linux and Alpine from their own
  # packages, which Docker's script does not cover.
  if ! command -v docker >/dev/null 2>&1; then
    say "→ putting in Docker ($PRETTY; a minute or two)"
    case "$DISTRO" in
      amzn) pkg_install docker || fail_log "Could not install Docker from Amazon Linux's packages." ;;
      alpine) pkg_install docker docker-cli-compose || fail_log "Could not install Docker from Alpine's packages." ;;
      rocky|almalinux|ol)
        { $SUDO dnf install -y -q dnf-plugins-core && $SUDO dnf config-manager --add-repo https://download.docker.com/linux/rhel/docker-ce.repo; } </dev/null >>"$LOG" 2>&1 \
          && pkg_install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin \
          || fail_log "Could not install Docker from Docker's packages for RHEL." ;;
      *)
        fetch https://get.docker.com "$WORK/get-docker.sh" >>"$LOG" 2>&1 || fail_log "Could not download Docker's install script from get.docker.com. Is the server online?"
        $SUDO sh "$WORK/get-docker.sh" </dev/null >>"$LOG" 2>&1 || fail_log "Docker's own install script could not put Docker on $PRETTY. Install Docker (https://docs.docker.com/engine/install/), then run this again." ;;
    esac
    command -v docker >/dev/null 2>&1 || fail_log "Docker was installed but is still not found. Open a new session and run this again."
  fi
  start_docker
  DV="$($SUDO docker version --format '{{.Server.Version}}' 2>/dev/null || true)"
  DVN="$(printf '%s' "$DV" | sed 's/[^0-9.].*$//')"
  if [ -n "$DVN" ] && ver_lt "$DVN" 24; then
    fail "Docker $DV is older than 24, which this needs. Update it with Docker's own script (curl -fsSL https://get.docker.com | sudo sh), then run this again."
  fi

  # Compose 2.24.4 or later (the kit keeps its database ports on this machine
  # with !override, which earlier versions do not read).
  CV="$(compose_version || true)"
  if [ -z "$CV" ] || ver_lt "$CV" 2.24.4; then
    if [ -z "$CV" ]; then say "→ putting in Docker Compose"; else say "→ Docker Compose $CV is older than 2.24.4: putting in the current one"; fi
    case "$(uname -m)" in
      x86_64|amd64) A=x86_64 ;; aarch64|arm64) A=aarch64 ;; armv7l|armv7) A=armv7 ;;
      *) fail "Docker Compose for $(uname -m) is not something this can fetch. Install Docker Compose 2.24.4 or later, then run this again." ;;
    esac
    PLUGINS="${PENTAL_COMPOSE_PLUGIN_DIR:-/usr/local/lib/docker/cli-plugins}"
    fetch "https://github.com/docker/compose/releases/latest/download/docker-compose-linux-$A" "$WORK/docker-compose" >>"$LOG" 2>&1 \
      || fail_log "Could not download Docker Compose from github.com. Is the server online?"
    { $SUDO mkdir -p "$PLUGINS" && $SUDO cp "$WORK/docker-compose" "$PLUGINS/docker-compose" && $SUDO chmod 755 "$PLUGINS/docker-compose"; } >>"$LOG" 2>&1 \
      || fail_log "Could not put Docker Compose in $PLUGINS."
    CV="$(compose_version || true)"
    if [ -z "$CV" ] || ver_lt "$CV" 2.24.4; then fail "Docker Compose is still not 2.24.4 or later here (${CV:-none}). Install it, then run this again."; fi
  fi

  # Docker as this user where it lets them, else through sudo; and this user
  # let in for next time, so docker needs no sudo from their next sign-in.
  LATER=""
  if [ -z "$SUDO" ] || docker info >/dev/null 2>&1; then
    D="docker"
  else
    D="$SUDO docker"
    ME="$(id -un)"
    if ! id -nG "$ME" 2>/dev/null | tr ' ' '\n' | grep -qx docker; then
      if { $SUDO usermod -aG docker "$ME" || $SUDO addgroup "$ME" docker; } </dev/null >>"$LOG" 2>&1; then LATER=1; fi
    fi
  fi

  say "→ fetching the newest $WHAT from $SITE"
  fetch "$SITE/downloads/$FILE" "$WORK/download.tar.gz" >>"$LOG" 2>&1 || fail_log "Could not download $SITE/downloads/$FILE. Can this server reach $SITE?"
  tar -xzf "$WORK/download.tar.gz" </dev/null >>"$LOG" 2>&1 || fail_log "The download would not unpack in $(pwd)."
  cd "$DIR"

  say "→ making its secrets (kept in $(pwd)/.env; an earlier .env keeps its own)"
  DOCKER="$D" bash ./pental-setup.sh "$HOST" "$PORTAL" </dev/null >"$WORK/setup.out" 2>&1 || { cat "$WORK/setup.out" >&2; fail "The setup stopped; what it said is above."; }

  # --build for both: the gateway is built from the folder, and the kit's
  # updater too, so a paste that brings a newer one starts the newer one.
  say "→ starting it (the first start downloads its images: a few minutes)"
  # 1818: [stated] Arian, of a first start on a 4 GB server that ended
  # "container supabase-auth is unhealthy": "fix and make instructions
  # seamless". A service still busy with its first start is waited for and
  # started again (the kit no longer has Docker wait on auth's health, so this
  # is the rare case); only one that has really stopped ends the setup, and
  # then what it said last is shown here, so nobody has to go and ask Docker.
  TRIES=0
  until $D compose up -d --build </dev/null; do
    TRIES=$((TRIES + 1))
    if [ "$TRIES" -ge "${PENTAL_START_TRIES:-3}" ]; then
      say ""
      say "It did not start. What each service that is not running said last:"
      for SVC in $($D compose ps --all --format '{{.Service}} {{.State}} {{.Health}}' </dev/null 2>/dev/null | awk '$2 != "running" || $3 == "unhealthy" { print $1 }'); do
        say ""
        say "── $SVC"
        $D compose logs --no-color --tail 30 "$SVC" </dev/null 2>&1 | sed 's/^/  /'
      done
      say ""
      fail "Run this same line again once that is put right: it keeps everything made so far. Stuck? Send what is above to hello@pental.io."
    fi
    say "→ a service is still on its first start; waiting a minute, then starting it again"
    sleep "${PENTAL_START_SECONDS:-60}"
  done

  TOKEN="$(sed -n 's/^SETUP_TOKEN=//p' .env | head -n 1)"
  ANON="$(sed -n 's/^ANON_KEY=//p' .env | head -n 1)"
  if [ "$KIND" = gateway ]; then PROBE="https://$HOST/health"; else PROBE="https://$HOST/auth/v1/health"; fi

  # 1817: does the name lead here yet? This server's public address, and the
  # name as public DNS has it (above main).
  IP="$(public_ip || true)"
  dns_where "$HOST"
  ST="$(a_check)"
  UP=""
  if [ "$ST" = ok ] || [ "$ST" = unknown ]; then
    say "→ waiting for https://$HOST to answer (its certificate comes once the name points at this server and ports 80 and 443 are open)"
    i=0
    while [ "$i" -lt "${PENTAL_WAIT_TRIES:-36}" ]; do
      if answers; then UP=1; break; fi
      i=$((i + 1)); sleep "${PENTAL_WAIT_SECONDS:-5}"
    done
  fi

  KEY=""
  if [ -n "$UP" ] && [ "$KIND" = gateway ]; then KEY="$(gateway_key)"; fi
  say ""
  say "Done. On pental.io, open Database, choose \"$PAGE\" and paste:"
  say ""
  say "  Address:          https://$HOST"
  if [ "$KIND" = gateway ]; then
    say "  Setup token:      $TOKEN"
    say "  Publishable key:  ${KEY:-(the wizard reads it itself)}"
  else
    say "  Publishable key:  $ANON"
  fi
  say ""
  if [ "$KIND" = gateway ]; then
    say "Its secrets are in $(pwd)/.env. Keep the setup token in your password manager: it applies schema"
    say "updates and moves the database later."
  else
    say "Every secret is in $(pwd)/.env, and the Studio dashboard is at https://$HOST behind the"
    say "DASHBOARD_USERNAME and DASHBOARD_PASSWORD in it. Keep that file safe."
  fi
  if [ -n "$LATER" ]; then
    say ""
    say "From your next sign-in, docker works without sudo here (you were added to the docker group);"
    say "until then put sudo in front of docker."
  fi

  # Not answering yet: the record to add, if the name does not lead here,
  # and the name and the address watched until both are right, with what is
  # wrong said as it is seen.
  if [ -z "$UP" ]; then
    if [ "$ST" = ok ]; then
      say ""
      say "  $HOST leads to this server, but https://$HOST does not answer yet: ports 80 and 443 must be"
      say "  open to the internet (in your cloud's firewall or security group too)."
    else
      show_a_record
      a_says "$ST"
    fi
    say "→ watching for it (leave this running, or stop it with Ctrl+C: the server carries on by itself)"
    SAID="$ST"; i=0
    while [ "$i" -lt "${PENTAL_DNS_TRIES:-80}" ]; do
      if [ "$ST" != ok ] && [ "$ST" != unknown ]; then
        ST="$(a_check)"
        if [ "$ST" != "$SAID" ]; then a_says "$ST"; SAID="$ST"; fi
      fi
      if [ "$ST" = ok ] || [ "$ST" = unknown ]; then
        if answers; then UP=1; break; fi
      fi
      i=$((i + 1)); sleep "${PENTAL_DNS_SECONDS:-15}"
    done
    if [ -n "$UP" ]; then
      say "→ https://$HOST answers, with its certificate. The page on pental.io sees it now."
      if [ "$KIND" = gateway ]; then
        KEY="$(gateway_key)"
        if [ -n "$KEY" ]; then say "  Publishable key:  $KEY"; fi
      fi
    else
      say ""
      say "https://$HOST does not answer from here yet. It will once the name points at this server (an A record"
      say "with this server's public IP address) and ports 80 and 443 are open to the internet (in your cloud's"
      say "firewall or security group too). It carries on by itself; the page on pental.io sees it when it does."
    fi
  fi
  rm -rf "$WORK"
}

# All of it read before any of it runs: pasted through a pipe, a script that
# ran as it arrived could stop half way, or be read by a command it starts.
main "$@"
