#!/usr/bin/env bash
#
# Purpose : Make, deploy and test apps for Federated Core, against the Core
#           in coreapp-dev's VM (coreapp-vm).
#
# coreapp new [--postgres] [--sso] <name>
#                          make a new app in ./<name> (with its own database,
#                          sign-in through the Core's Authelia, or both)
# coreapp deploy [--recreate]
#                          build, copy to the Core, install or update
#                          (--recreate: a new container even if nothing changed)
# coreapp check            the app answers at https://<name>.<domain>/
# coreapp status           its container, address and URL
# coreapp logs [-f]        its log
# coreapp shell [command]  a shell in its container, or run one command there
# coreapp remove           uninstall it from the Core (asks first)
# coreapp list             the apps on the Core installed this way
#
# Run everything but `new` and `list` in the app's folder (the one with
# coreapp.toml). COREAPP_VM picks the VM (default coreserver).

set -euo pipefail

SELF_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
TEMPLATES="$(dirname "$SELF_DIR")/templates"
TEMPLATE="$TEMPLATES/app"
# The installer that runs on the Core (coreapps), and where it goes there
INSTALLER="$(dirname "$SELF_DIR")/core"
REMOTE_INSTALLER=/opt/coreapps
DATA="$HOME/.local/share/coreapp-dev"
SSH_KEY="$DATA/ssh/id_ed25519"
KNOWN_HOSTS="$DATA/ssh/known_hosts"
VM="${COREAPP_VM:-coreserver}"

die() { echo "$*" >&2; exit 1; }

usage() {
  sed -n '/^# coreapp /s/^# //p' "${BASH_SOURCE[0]}"
}

# --- The Core -------------------------------------------------------------

CORE_IP=""
# Look up the VM's address once, in this shell (not in a $(...) subshell,
# which would forget it)
init_core() {
  if [[ -z "$CORE_IP" ]]; then
    CORE_IP="$("$SELF_DIR/coreapp-vm" ip "$VM" 2> /dev/null)" \
      || die "The Core's VM '$VM' isn't running: coreapp-vm start $VM"
  fi
}
core_ip() { init_core; echo "$CORE_IP"; }

# Run a shell command on the Core as root (stdin is passed through)
core() {
  ssh -i "$SSH_KEY" -o UserKnownHostsFile="$KNOWN_HOSTS" \
    -o StrictHostKeyChecking=accept-new -o BatchMode=yes \
    "root@$(core_ip)" "$1"
}

# The same, with a terminal (for shells and following logs)
core_tty() {
  ssh -t -i "$SSH_KEY" -o UserKnownHostsFile="$KNOWN_HOSTS" \
    -o StrictHostKeyChecking=accept-new "root@$(core_ip)" "$1"
}

DOMAIN=""
core_domain() {
  if [[ -z "$DOMAIN" ]]; then
    # shellcheck disable=SC2016 # expanded on the Core
    DOMAIN="$(core '. /etc/federated; echo "$DOMAIN"')"
    [[ -n "$DOMAIN" ]] || die "The VM has no Core installed yet (no DOMAIN in /etc/federated)."
  fi
  echo "$DOMAIN"
}

# --- The app in the current folder ---------------------------------------

# From coreapp.toml, as checked by the installer
NAME="" TITLE="" VERSION="" IMAGE="" PORT="" HEALTH="" NEEDS=""
load_app() {
  local values key value
  [[ -f coreapp.toml ]] \
    || die "No app here: run this in an app's folder (one with coreapp.toml), or make one with coreapp new <name>."
  values="$(python3 "$INSTALLER/coreapps" manifest .)" || exit 1
  while IFS='=' read -r key value; do
    case "$key" in
      name) NAME="$value" ;;
      title) TITLE="$value" ;;
      version) VERSION="$value" ;;
      image) IMAGE="$value" ;;
      port) PORT="$value" ;;
      health) HEALTH="$value" ;;
      needs) NEEDS="$value" ;;
    esac
  done <<< "$values"
  init_core
}

image() { echo "$IMAGE:$VERSION"; }

# Put the installer on the Core, as this coreapp-dev has it
sync_installer() {
  tar -C "$INSTALLER" --exclude=__pycache__ --exclude=.claude -cf - . | core "
    set -e
    rm -rf $REMOTE_INSTALLER.new && mkdir -p $REMOTE_INSTALLER.new
    tar --no-same-owner -xf - -C $REMOTE_INSTALLER.new
    rm -rf $REMOTE_INSTALLER && mv $REMOTE_INSTALLER.new $REMOTE_INSTALLER"
}

# Run the installer on the Core with this app's coreapp.toml and icon.png,
# copied to a temporary folder there: coreapps <command> [options] <folder>
installer() {
  local files=(coreapp.toml)
  [[ -f icon.png ]] && files+=(icon.png)
  tar -cf - "${files[@]}" | core "
    d=\$(mktemp -d) && tar --no-same-owner -xf - -C \$d || exit 1
    $REMOTE_INSTALLER/coreapps $* \$d; status=\$?
    rm -rf \$d; exit \$status"
}

# --- new --------------------------------------------------------------------

# Lay an overlay over the app in $1: its files replace the app's, except
# *.append (added to the end of the app's file), .remove (app files it
# doesn't use) and .needs (what it needs from the Core, for coreapp.toml)
apply_overlay() {
  local app="$1" overlay="$2" f
  tar -C "$overlay" --exclude=.claude --exclude=.remove --exclude=.needs \
    --exclude='*.append' -cf - . | tar -C "$app" -xf -
  for f in "$overlay"/*.append; do
    [[ -e "$f" ]] && cat "$f" >> "$app/$(basename "$f" .append)"
  done
  if [[ -f "$overlay/.remove" ]]; then
    while read -r f; do [[ -n "$f" ]] && rm -rf "${app:?}/$f"; done < "$overlay/.remove"
  fi
}

cmd_new() {
  local name="" postgres="" sso="" title dbname f needs="" what=""
  local overlays=()
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --postgres) postgres=1 ;;
      --sso) sso=1 ;;
      -*) die "Unknown option $1. Usage: coreapp new [--postgres] [--sso] <name>" ;;
      *) name="$1" ;;
    esac
    shift
  done
  [[ -d "$TEMPLATE" ]] || die "The app template is missing: $TEMPLATE"
  [[ -n "$name" ]] || die "Usage: coreapp new [--postgres] [--sso] <name>   (lowercase letters, digits and -)"
  [[ "$name" =~ ^[a-z]([a-z0-9-]{0,29}[a-z0-9])$ ]] \
    || die "'$name': use 2-31 lowercase letters, digits and -, starting with a letter and not ending with -. It becomes https://$name.<domain>."
  [[ ! -e "$name" ]] || die "./$name already exists."

  # In this order; with both, the combined example app goes on top
  [[ -n "$postgres" ]] && overlays+=("$TEMPLATES/postgres")
  [[ -n "$sso" ]] && overlays+=("$TEMPLATES/sso")
  [[ -n "$postgres" && -n "$sso" ]] && overlays+=("$TEMPLATES/postgres-sso")
  for f in "${overlays[@]}"; do
    [[ -d "$f" ]] || die "The template $f is missing."
  done

  # "my-app" -> "My App". The database name is the installer's (coreapps)
  title="$(echo "$name" | sed -E 's/-/ /g; s/(^| )([a-z])/\1\u\2/g')"
  dbname="coreapp_${name//-/_}"

  mkdir "$name"
  tar -C "$TEMPLATE" --exclude=.claude -cf - . | tar -C "$name" -xf -
  for f in "${overlays[@]}"; do
    apply_overlay "$name" "$f"
    [[ -f "$f/.needs" ]] && needs="$needs, \"$(cat "$f/.needs")\""
  done
  sed -i "s/^needs = .*/needs = [${needs#, }]/" "$name/coreapp.toml"
  # The example apps with a database or sign-in have a /health path
  [[ ${#overlays[@]} -gt 0 ]] && sed -i 's|^health = .*|health = "/health"|' "$name/coreapp.toml"

  while IFS= read -r -d '' f; do
    sed -i -e "s/{{NAME}}/$name/g" -e "s/{{TITLE}}/$title/g" -e "s/{{DBNAME}}/$dbname/g" "$f"
  done < <(find "$name" -type f ! -name '*.png' -print0)

  [[ -n "$postgres" ]] && what=", with a database"
  [[ -n "$sso" ]] && what="$what, with sign-in through Authelia"
  echo "Made $title in ./$name$what."
  echo "Next: cd $name && coreapp deploy"
}

# --- deploy -----------------------------------------------------------------

cmd_deploy() {
  local plan state tier answer local_id core_id addon="" recreate=""
  case "${1:-}" in
    --recreate) recreate=--recreate ;;
    "") ;;
    *) die "Usage: coreapp deploy [--recreate]" ;;
  esac
  load_app

  echo "Updating the installer on the Core ($REMOTE_INSTALLER)..."
  sync_installer
  # What installing would do (and whether the Core refuses it: name taken...)
  plan="$(installer plan)" || exit 1
  state="$(sed -n 's/^state=//p' <<< "$plan")"
  tier="$(sed -n 's/^tier=//p' <<< "$plan")"
  if grep -qx 'addon=yes' <<< "$plan"; then
    echo "This Core's tier is '$tier'. Installing records '$NAME' as an add-on app"
    echo "(ADDON_APPS in /etc/federated), which Federated may bill for."
    read -r -p "Install anyway? [y/N] " answer
    [[ "$answer" =~ ^[Yy] ]] || die "Not deployed."
    addon=--addon-ok
  fi

  echo "Building $(image)..."
  docker build -q -t "$(image)" . > /dev/null

  # localhost/ images exist only where they're copied; others the Core can
  # pull, but while developing, the one just built is the one to test
  local_id="$(docker image inspect -f '{{.Id}}' "$(image)")"
  core_id="$(core "docker image inspect -f '{{.Id}}' $(image) 2> /dev/null || true")"
  if [[ "$local_id" != "$core_id" ]]; then
    echo "Copying the image to the Core ($(docker image inspect -f '{{.Size}}' "$(image)" | numfmt --to=iec))..."
    docker save "$(image)" | core "docker load -q > /dev/null"
  else
    echo "The Core already has this image."
  fi

  # Install, or update (which recreates the container if the image changed,
  # even under the same version)
  installer install $addon $recreate || exit 1
  [[ "$state" == new ]] && echo "(coreapp check tests it from the internet.)"
  return 0
}

# --- check, status, logs, shell, remove ------------------------------------

cmd_check() {
  local domain url result code verify tries=24
  load_app
  domain="$(core_domain)"
  url="https://$NAME.$domain$HEALTH"
  echo "Checking $url (expecting HTTP 2xx and a valid certificate)..."
  # A new app's certificate can take a minute: traefik gets it from Let's
  # Encrypt through the Core's DNS
  while true; do
    result="$(curl -sS -o /dev/null --max-time 15 -w '%{http_code} %{ssl_verify_result}' "$url" 2>&1 || true)"
    code="${result%% *}"
    verify="${result##* }"
    if [[ "$code" =~ ^2 && "$verify" == 0 ]]; then
      echo "OK: HTTP $code, valid certificate."
      return 0
    fi
    tries=$((tries - 1))
    if ((tries == 0)); then break; fi
    sleep 5
  done
  echo "Not OK: $result (HTTP code, then 0 if the certificate is valid)." >&2
  # Is it the app, or the way in?
  result="$(curl -sSk -o /dev/null --max-time 15 -w '%{http_code}' \
    --resolve "$NAME.$domain:443:$(core_ip)" "$url" 2>&1 || true)"
  echo "Straight to the VM, skipping DNS and the relay: HTTP $result." >&2
  exit 1
}

cmd_status() {
  local domain
  load_app
  domain="$(core_domain)"
  core "docker ps -a --filter name='^$NAME\$' --format 'Container: {{.Names}}  {{.Status}}  image {{.Image}}'
    [ -n \"\$(docker ps -aq --filter name='^$NAME\$')\" ] || echo 'Not installed on the Core.'"
  echo "App: $TITLE $(image)"
  echo "Address on the Core: $(core "sed -n 's/^INTERNAL_IP=//p' /federated/services/$NAME/service 2> /dev/null"), port $PORT"
  echo "Needs: ${NEEDS:-nothing}"
  echo "URL: https://$NAME.$domain/"
}

cmd_logs() {
  load_app
  if [[ "${1:-}" == -f ]]; then
    core_tty "docker logs -f --tail 50 $NAME"
  else
    core "docker logs --tail 200 $NAME 2>&1"
  fi
}

cmd_shell() {
  load_app
  if [[ $# -gt 0 ]]; then
    # One command, without a terminal, so scripts and agents can use it:
    # coreapp shell 'ls -l /data'
    core "docker exec $NAME sh -c $(printf '%q' "$*")"
  else
    core_tty "docker exec -it $NAME sh -c 'command -v bash > /dev/null && exec bash || exec sh'"
  fi
}

cmd_remove() {
  local answer
  load_app
  echo "This uninstalls $NAME from the Core in '$VM', with its settings and data"
  echo "there${NEEDS:+ (and what it has in: $NEEDS)}. This folder stays as it is."
  read -r -p "Remove it? [y/N] " answer
  [[ "$answer" =~ ^[Yy] ]] || die "Not removed."
  sync_installer
  core "$REMOTE_INSTALLER/coreapps remove $NAME"
}

cmd_list() {
  init_core
  sync_installer
  core "$REMOTE_INSTALLER/coreapps list"
}

cmd="${1:-help}"
[[ $# -gt 0 ]] && shift
case "$cmd" in
  new) cmd_new "$@" ;;
  deploy) cmd_deploy "$@" ;;
  check) cmd_check ;;
  status) cmd_status ;;
  logs) cmd_logs "$@" ;;
  shell) cmd_shell "$@" ;;
  remove | rm) cmd_remove ;;
  list | ls) cmd_list ;;
  help | -h | --help) usage ;;
  *) usage >&2; exit 1 ;;
esac
