#!/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 <name>       make a new app in ./<name>
# coreapp deploy           build, copy to the Core, install or update
# coreapp check            the app answers at https://<name>.<domain>/
# coreapp status           its container, address and URL
# coreapp logs [-f]        its log
# coreapp shell            a shell in its container
# coreapp remove           uninstall it from the Core (asks first)
#
# Run everything but `new` in the app's folder. COREAPP_VM picks the VM
# (default coreserver).

set -euo pipefail

SELF_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
TEMPLATE="$(dirname "$SELF_DIR")/templates/app"
DATA="$HOME/.local/share/coreapp-dev"
# The INTERNAL_IP given to each app made on this machine: "name ip" lines
ADDRESSES="$DATA/app-addresses"
# Apps get addresses here, away from Federated's apps in 192.168.0.x (both
# are in the Core's 192.168.0.0/16 network)
PREFIX=192.168.200
SSH_KEY="$DATA/ssh/id_ed25519"
KNOWN_HOSTS="$DATA/ssh/known_hosts"
VM="${COREAPP_VM:-coreserver}"
# What the Core installs an app from; the rest of the folder stays here
CORE_FILES=(service docker-compose.yml.in env.in install uninstall icon.png timers services upgrade)

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 ---------------------------------------

# NAME is the app's id (its folder on the Core); TITLE is NAME in service
NAME="" TITLE="" CONTAINER="" VERSION="" INTERNAL_IP="" MONITOR="" HIDDEN=""
load_app() {
  [[ -f service && -f install ]] \
    || die "No app here: run this in an app's folder (one with service and install), or make one with coreapp new <name>."
  # service is shell variables, as the Core reads it
  set +u
  # shellcheck source=/dev/null
  . ./service
  set -u
  TITLE="$NAME"
  NAME="$(sed -n 's/^installGeneric[[:space:]]\{1,\}\([a-z0-9-]*\).*/\1/p' install | head -n 1)"
  [[ -n "$NAME" ]] || die "install doesn't say which app it is (installGeneric <name>)."
  [[ -n "$CONTAINER" && -n "$VERSION" && -n "$INTERNAL_IP" ]] \
    || die "service needs CONTAINER, VERSION and INTERNAL_IP."
  init_core
}

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

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

next_address() {
  local n
  for n in $(seq 10 250); do
    if ! grep -qs " $PREFIX\.$n\$" "$ADDRESSES"; then
      echo "$PREFIX.$n"
      return
    fi
  done
  die "All addresses in $PREFIX.10-250 are taken (see $ADDRESSES)."
}

cmd_new() {
  local name="${1:-}" title ip f
  [[ -d "$TEMPLATE" ]] || die "The app template is missing: $TEMPLATE"
  [[ -n "$name" ]] || die "Usage: coreapp new <name>   (lowercase letters, digits and -)"
  [[ "$name" =~ ^[a-z][a-z0-9-]{1,30}$ ]] \
    || die "'$name': use 2-31 lowercase letters, digits and -, starting with a letter. It becomes https://$name.<domain>."
  [[ ! -e "$name" ]] || die "./$name already exists."

  ip="$(grep -s "^$name " "$ADDRESSES" | cut -d' ' -f2 || true)"
  if [[ -z "$ip" ]]; then
    ip="$(next_address)"
    mkdir -p "$DATA"
    echo "$name $ip" >> "$ADDRESSES"
  fi
  # "my-app" -> "My App"
  title="$(echo "$name" | sed -E 's/-/ /g; s/(^| )([a-z])/\1\u\2/g')"

  mkdir "$name"
  tar -C "$TEMPLATE" --exclude=.claude -cf - . | tar -C "$name" -xf -
  while IFS= read -r -d '' f; do
    sed -i -e "s/{{NAME}}/$name/g" -e "s/{{TITLE}}/$title/g" -e "s/{{IP}}/$ip/g" "$f"
  done < <(find "$name" -type f ! -name '*.png' -print0)

  echo "Made $title in ./$name (address on the Core: $ip)."
  echo "Next: cd $name && coreapp deploy"
}

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

cmd_deploy() {
  local domain info state theirs tier used local_id core_id f log files=()
  load_app
  domain="$(core_domain)"

  # What the Core has: is the app installed, is the name or address taken?
  info="$(core "
    . /etc/federated
    echo \"tier \$TIER\"
    [ -d /federated/apps/$NAME ] && echo installed || echo new
    if [ -f /federated/services/$NAME/service ]; then
      echo \"theirs \$(sed -n 's/^CONTAINER=//p' /federated/services/$NAME/service)\"
    fi
    docker network inspect core -f '{{range .Containers}}{{.Name}} {{.IPv4Address}}{{println}}{{end}}' \
      | grep ' $INTERNAL_IP/' | sed 's/^/used /' || true
  ")"
  tier="$(sed -n 's/^tier //p' <<< "$info")"
  state="$(grep -xE 'installed|new' <<< "$info")"
  theirs="$(sed -n 's/^theirs //p' <<< "$info")"
  used="$(sed -n 's/^used \([^ ]*\) .*/\1/p' <<< "$info" | grep -vx "$NAME" || true)"

  if [[ -n "$theirs" && "$theirs" != "$CONTAINER" ]]; then
    die "The Core already has an app called '$NAME' ($theirs). Pick another name."
  fi
  if [[ -n "$used" ]]; then
    die "$INTERNAL_IP is already used on the Core by: $used. Change INTERNAL_IP in service (and docker-compose.yml.in)."
  fi
  if [[ "$state" == new && "${tier,,}" != enterprise && "$HIDDEN" != true ]]; 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] " f
    [[ "$f" =~ ^[Yy] ]] || die "Not deployed. HIDDEN=true in service keeps an app off that list."
  fi

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

  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

  echo "Copying the app to /federated/services/$NAME..."
  for f in "${CORE_FILES[@]}"; do [[ -e "$f" ]] && files+=("$f"); done
  tar -cf - "${files[@]}" | core "
    set -e
    d=/federated/services/$NAME
    rm -rf \$d.new && mkdir -p \$d.new && tar --no-same-owner -xf - -C \$d.new
    # No MONITOR on the Core: installapp would register it with Federated's
    # external monitoring, which apps in development shouldn't be in
    sed -i '/^MONITOR=/d' \$d.new/service
    rm -rf \$d && mv \$d.new \$d"

  if [[ "$state" == new ]]; then
    echo "Installing it (the Core's installapp)..."
    mkdir -p "$DATA/logs"
    log="$DATA/logs/$NAME-install.log"
    # installapp traces what it runs, tokens included: keep that private
    : > "$log" && chmod 600 "$log"
    if ! core "/federated/bin/installapp -n $NAME" > "$log" 2>&1; then
      tail -n 20 "$log" >&2
      die "installapp failed (whole log: $log)."
    fi
    # installapp's start step only knows Federated's own apps (the list in
    # /federated/lib/functions.sh), so start it the way the Core does
    core "docker compose -f /federated/apps/$NAME/docker-compose.yml -p $NAME up -d 2>&1 | grep -v '^ *Container ' || true"
  else
    # Keep .env (its random secrets); redo the compose file, which may have
    # changed, and the version
    echo "Updating it..."
    core "
      set -e
      cd /federated
      . /etc/federated
      . lib/helpers.sh
      . services/$NAME/service
      templatize services/$NAME/docker-compose.yml.in > apps/$NAME/docker-compose.yml
      sed -i 's/^IMAGE_VERSION=.*/IMAGE_VERSION=$VERSION/' apps/$NAME/.env
      docker compose -f apps/$NAME/docker-compose.yml -p $NAME up -d --remove-orphans 2>&1 | grep -v '^ *Container .* Running\$' || true"
  fi

  if [[ "$(core "docker inspect -f '{{.State.Status}}' $NAME 2> /dev/null || true")" != running ]]; then
    core "docker logs --tail 20 $NAME 2>&1" >&2 || true
    die "$NAME isn't running on the Core (its log is above, if it has one)."
  fi
  echo "Deployed: https://$NAME.$domain/  (coreapp check tests it)"
}

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

cmd_check() {
  local domain url expect result code verify tries=24
  load_app
  domain="$(core_domain)"
  url="https://$NAME.$domain/"
  expect="http_2xx"
  if [[ -n "$MONITOR" ]]; then
    url="${MONITOR%%|*}"
    url="${url//@DOMAIN@/$domain}"
    [[ "$MONITOR" == *"|"* ]] && expect="${MONITOR#*|}"
  fi
  echo "Checking $url (expecting $expect)..."
  # 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 $VERSION ($CONTAINER)"
  echo "Address on the Core: $INTERNAL_IP"
  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
  core_tty "docker exec -it $NAME sh -c 'command -v bash > /dev/null && exec bash || exec sh'"
}

cmd_remove() {
  local answer log
  load_app
  echo "This uninstalls $NAME from the Core in '$VM', with its settings and data"
  echo "there. This folder stays as it is."
  read -r -p "Remove it? [y/N] " answer
  [[ "$answer" =~ ^[Yy] ]] || die "Not removed."
  mkdir -p "$DATA/logs"
  log="$DATA/logs/$NAME-remove.log"
  # uninstallapp traces what it runs, tokens included: keep that private
  : > "$log" && chmod 600 "$log"
  if ! core "
    set -e
    if [ -d /federated/apps/$NAME ]; then /federated/bin/uninstallapp $NAME; fi
    rm -rf /federated/services/$NAME
    docker image ls -q '$CONTAINER' | xargs -r docker image rm -f" > "$log" 2>&1; then
    tail -n 20 "$log" >&2
    die "Removing failed (whole log: $log)."
  fi
  echo "Removed $NAME from the Core."
}

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 ;;
  help | -h | --help) usage ;;
  *) usage >&2; exit 1 ;;
esac
