#!/bin/sh
# THE PENTAL GATEWAY IN YOUR CLOUD, FROM macOS OR LINUX, IN ONE PASTE (1827).
#
#   curl -fsSL --retry 3 https://pental.io/downloads/pental-gateway.sh | sh -s -- aws <stack> <region> <portal-url> <gateway-name>
#
# (azure <resource-group> <region> <portal-url>, or gcp "" <region>
# <portal-url> for the project gcloud is set to: what follows the cloud goes
# to its deploy script as it is.)
#
# [stated] Arian, after pasting the gateway's command: "its just hanging doesnt
# show progress or anything remember seamless modern professional process".
# The download had stalled, silently, then ended with "curl: (56) Recv
# failure: Connection was reset". This fetches the newest gateway into a
# pental-gateway folder in your home folder, showing it come in, and tries
# again by itself when a connection drops or stalls. It uses what arrived only
# when it matches the SHA-256 pental.io publishes for it, unpacks it over the
# folder (the secrets a deploy keeps there stay), and runs the deploy script
# for the cloud named first, at this terminal. Pasted again, it updates the
# gateway in place.
#
# Everything happens in main, called on the last line, so a download of this
# script cut off part-way runs nothing.
set -eu

SITE="${PENTAL_SITE:-https://pental.io}"
SITE="${SITE%/}"
TRIES="${PENTAL_DOWNLOAD_TRIES:-5}"

say() { printf '%s\n' "$*"; }
fail() { printf '%s\n' "$*" >&2; exit 1; }

# get <url> <file> [quiet]: whole, or not at all; again after a dropped or
# stalled connection.
get() {
  g_try=1
  while [ "$g_try" -le "$TRIES" ]; do
    rm -f "$2"
    if [ "${3:-}" = quiet ]; then
      curl -fsSL --connect-timeout 15 --speed-limit 1 --speed-time 30 -o "$2" "$1" && return 0
    else
      curl -# -fL --connect-timeout 15 --speed-limit 1 --speed-time 30 -o "$2" "$1" && return 0
    fi
    if [ "$g_try" -lt "$TRIES" ]; then
      say "  the connection dropped; trying again ($((g_try + 1)) of $TRIES)"
      sleep $((g_try * 2))
    fi
    g_try=$((g_try + 1))
  done
  return 1
}

# A value from the gateway's entry in kits.json ("tar" for its .tar.gz).
kit_value() {
  awk -v key="$2" '
    /"gateway"[[:space:]]*:[[:space:]]*\{/ { g = 1 }
    g && /"tar"[[:space:]]*:[[:space:]]*\{/ { t = 1 }
    g && t && $0 ~ "\"" key "\"[[:space:]]*:" { sub(/^[^:]*:[[:space:]]*/, ""); gsub(/[",]/, ""); print; exit }
  ' "$1"
}
sha256_of() {
  if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1
  else shasum -a 256 "$1" | cut -d' ' -f1; fi
}

main() {
  case "${1:-}" in
    aws) CLOUD_NAME="Amazon Web Services" ;;
    azure) CLOUD_NAME="Microsoft Azure" ;;
    gcp) CLOUD_NAME="Google Cloud" ;;
    *) fail "Usage: curl -fsSL $SITE/downloads/pental-gateway.sh | sh -s -- <aws|azure|gcp> <what the deploy script for that cloud takes>. The Database step on pental.io writes the whole command for you." ;;
  esac
  CLOUD="$1"; shift
  command -v curl >/dev/null 2>&1 || fail "This needs curl, which every Mac and most Linux has. Install it, then run this again."
  command -v tar >/dev/null 2>&1 || fail "This needs tar. Install it, then run this again."
  DIR="$HOME/pental-gateway"
  WHY="Something between this computer and pental.io keeps cutting the download off (a VPN, a proxy, or security software that inspects downloads). Try again on another connection, or download the gateway from the Database step on pental.io, unpack it into your home folder, and run deploy/$CLOUD/deploy.sh from the pental-gateway folder."

  say ""
  say "Pental gateway, for $CLOUD_NAME, from $SITE"
  say ""
  WORK="$(mktemp -d "${TMPDIR:-/tmp}/pental-gateway.XXXXXX")"
  trap 'rm -rf "$WORK"' EXIT
  get "$SITE/downloads/kits.json" "$WORK/kits.json" quiet || fail "Could not reach $SITE. $WHY"
  URL="$(kit_value "$WORK/kits.json" url)"; SHA="$(kit_value "$WORK/kits.json" sha256)"; BYTES="$(kit_value "$WORK/kits.json" bytes)"
  VER="$(awk '/"gateway"[[:space:]]*:[[:space:]]*\{/ { g = 1 } g && /"version"[[:space:]]*:/ { sub(/^[^:]*:[[:space:]]*/, ""); gsub(/[",]/, ""); print; exit }' "$WORK/kits.json")"
  [ -n "$URL" ] && [ -n "$SHA" ] || fail "$SITE did not say which gateway is current. Try again in a minute."
  say "→ downloading the gateway $VER ($(( (${BYTES:-0} + 1023) / 1024 )) KB)"
  get "$SITE$URL" "$WORK/gateway.tar.gz" || fail "The download did not finish. $WHY"
  [ "$(sha256_of "$WORK/gateway.tar.gz")" = "$SHA" ] || fail "What arrived is not the gateway $SITE publishes (its SHA-256 does not match), so it was not used. Run this again. $WHY"
  say "  checked: it matches the SHA-256 $SITE publishes for it"

  # Unpacked over the folder; anything else there (the secrets a deploy
  # keeps) stays as it is. Only what is under pental-gateway/ is taken.
  say "→ unpacking it into $DIR"
  if tar -tzf "$WORK/gateway.tar.gz" | grep -qv '^pental-gateway/'; then fail "The download holds a file outside its own folder, so it was not unpacked."; fi
  if tar -tzf "$WORK/gateway.tar.gz" | grep -q '\.\./'; then fail "The download holds a file outside its own folder, so it was not unpacked."; fi
  tar -xzf "$WORK/gateway.tar.gz" -C "$HOME"
  say "  $(tar -tzf "$WORK/gateway.tar.gz" | grep -cv '/$') files; anything of yours already in the folder stays as it is"
  rm -rf "$WORK"; trap - EXIT

  SCRIPT="$DIR/deploy/$CLOUD/deploy.sh"
  [ -f "$SCRIPT" ] || fail "The gateway arrived without deploy/$CLOUD/deploy.sh. Try again in a minute."
  command -v bash >/dev/null 2>&1 || fail "The deploy script needs bash, which this computer does not have. Install it, then run this again."
  # Pasted as curl | sh, this script's input is the download: the deploy's is
  # the terminal, so it can sign you in and ask.
  if [ -t 1 ] && (exec </dev/tty) 2>/dev/null; then exec bash "$SCRIPT" "$@" </dev/tty; fi
  exec bash "$SCRIPT" "$@"
}

main "$@"
