#!/usr/bin/env bash
# Deploy OOS (oos-singlecube, oos-tesseract, oos-service) on the dev server.
#
# Run it on the dev server as the devgroup user:
#   ssh dev-server 'sudo -u devgroup /var/www/go-projects/oos-service/deploy/dev/deploy.sh [branch]'
#
#   deploy.sh              deploy main
#   deploy.sh <branch>     deploy a branch (a repo without that branch stays on main)
#   deploy.sh --restart    restart only, no pull and no build
#   deploy.sh --status     show what is deployed and running
#
# Settings can be overridden with environment variables: OOS_ROOT, OOS_PORT,
# CDN_PORT, CDN_PATH. See deploy/dev/README.md.

set -euo pipefail

ROOT=${OOS_ROOT:-/var/www/go-projects}
OOS_PORT=${OOS_PORT:-8082}      # oos-service; nginx proxies uat-<site>.admedia.com here
CDN_PORT=${CDN_PORT:-8888}      # oos-tesseract bundle; nginx proxies /oos/ here
CDN_PATH=${CDN_PATH:-/oos}      # tesseract_cdn_url, relative to each site's domain
GO_BIN=/usr/local/go/bin
LOG_DIR=$ROOT/logs
REPOS=(oos-singlecube oos-tesseract oos-service)

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

# Pids listening on a TCP port (own processes only, which is what we start).
listeners() { ss -ltnpH "sport = :$1" 2>/dev/null | grep -o 'pid=[0-9]*' | cut -d= -f2 | sort -u || true; }

repo_summary() {
  for r in "${REPOS[@]}"; do
    printf '  %-15s %s  (%s)\n' "$r" "$(git -C "$ROOT/$r" log -1 --format='%h %s' | cut -c1-70)" \
      "$(git -C "$ROOT/$r" rev-parse --abbrev-ref HEAD)"
  done
}

show_status() {
  say "Deployed commits"; repo_summary
  say "Listening"
  printf '  oos-service :%s  pid %s\n' "$OOS_PORT" "$(listeners "$OOS_PORT" | tr '\n' ' ')"
  printf '  tesseract   :%s  pid %s\n' "$CDN_PORT" "$(listeners "$CDN_PORT" | tr '\n' ' ')"
  printf '  health-check: '; curl -s -m 5 -o /dev/null -w '%{http_code}\n' "http://127.0.0.1:$OOS_PORT/health-check" || true
}

update_repo() {
  local r=$1 branch=$2 target=$2
  cd "$ROOT/$r"
  git fetch -q origin
  git rev-parse -q --verify "origin/$branch" >/dev/null || { echo "  $r has no branch $branch, using main"; target=main; }

  # Files the deploy itself changes; everything else must be clean.
  local f
  for f in config.json tsconfig.tsbuildinfo; do
    if git ls-files --error-unmatch "$f" >/dev/null 2>&1; then git checkout -q -- "$f"; fi
  done
  local dirty
  dirty=$(git status --porcelain --untracked-files=no)
  [ -z "$dirty" ] || die "$r has local changes, commit or discard them first:
$dirty"

  git checkout -q "$target" 2>/dev/null || git checkout -q -b "$target" "origin/$target"
  git merge -q --ff-only "origin/$target" || die "$r: $target cannot be fast-forwarded (local commits on the server?)"
  echo "  $r -> $target @ $(git rev-parse --short HEAD)"
}

run_logged() { # run_logged <logfile> <cmd...>
  local log=$1; shift
  "$@" >"$log" 2>&1 || { tail -25 "$log"; die "failed: $* (full log: $log)"; }
}

build_frontend() {
  # The lockfiles point at an internal npm registry the server cannot resolve, so use
  # the public one. --replace-registry-host does not touch the lockfiles.
  local npm_ci=(npm ci --no-audit --no-fund --replace-registry-host=always)
  say "Build oos-singlecube (dependencies)"
  cd "$ROOT/oos-singlecube"
  run_logged "$LOG_DIR/build-singlecube.log" "${npm_ci[@]}"
  say "Build oos-tesseract"
  cd "$ROOT/oos-tesseract"
  run_logged "$LOG_DIR/build-tesseract.log" "${npm_ci[@]}"
  run_logged "$LOG_DIR/build-tesseract.log" npm run build
  git checkout -q -- tsconfig.tsbuildinfo 2>/dev/null || true   # tracked file the build rewrites
  [ -s "$ROOT/oos-tesseract/dist/tesseract.js" ] || die "oos-tesseract/dist/tesseract.js was not built"
}

build_service() {
  say "Build oos-service"
  cd "$ROOT/oos-service"
  local version; version=$(git describe --tags --always --dirty 2>/dev/null || echo dev)
  PATH=$GO_BIN:$PATH run_logged "$LOG_DIR/build-service.log" \
    go build -ldflags "-X bitbucket.org/imediabrands/oos-service/healthchecks.version=$version" -o bin/oos-service .
}

write_config() {
  say "Write oos-service/config.json (port $OOS_PORT, bundle $CDN_PATH)"
  # Start from the dev environment file (it holds the API keys); never print it.
  OOS_PORT=$OOS_PORT CDN_PATH=$CDN_PATH ROOT=$ROOT python3 - <<'PY'
import json, os
root = os.environ["ROOT"]
c = json.load(open(f"{root}/oos-service/environments/dev/config.json"))
c["port"] = int(os.environ["OOS_PORT"])
c["hostname"] = "0.0.0.0"
c["tesseract_cdn_url"] = os.environ["CDN_PATH"]
json.dump(c, open(f"{root}/oos-service/config.json", "w"), indent=2)
PY
}

stop_services() {
  say "Stop services"
  local port pid
  for port in "$OOS_PORT" "$CDN_PORT"; do
    for pid in $(listeners "$port"); do kill "$pid" && echo "  stopped pid $pid on :$port"; done
  done
  # oos-service takes about 11 seconds to shut down.
  for _ in $(seq 1 30); do
    [ -z "$(listeners "$OOS_PORT")$(listeners "$CDN_PORT")" ] && return 0
    sleep 1
  done
  die "ports $OOS_PORT/$CDN_PORT are still in use after 30 seconds"
}

start_services() {
  say "Start services"
  cd "$ROOT/oos-tesseract"
  setsid nohup npx vite preview --host 0.0.0.0 --port "$CDN_PORT" --strictPort \
    >"$LOG_DIR/tesseract.log" 2>&1 </dev/null &
  cd "$ROOT/oos-service"
  setsid nohup ./bin/oos-service >"$LOG_DIR/oos-service.log" 2>&1 </dev/null &
}

verify() {
  say "Check"
  local ok=0
  for _ in $(seq 1 20); do
    if curl -fs -m 3 -o /dev/null "http://127.0.0.1:$OOS_PORT/health-check" \
       && curl -fs -m 3 -o /dev/null "http://127.0.0.1:$CDN_PORT/tesseract.js"; then ok=1; break; fi
    sleep 1
  done
  [ "$ok" = 1 ] || { tail -15 "$LOG_DIR/oos-service.log" "$LOG_DIR/tesseract.log"; die "services did not come up"; }
  echo "  oos-service  :$OOS_PORT  health-check OK"
  echo "  tesseract    :$CDN_PORT  tesseract.js OK"
  local title
  title=$(curl -s -m 8 -H 'Host: uat-bodytheory.admedia.com' "http://127.0.0.1:$OOS_PORT/" | grep -o '<title>[^<]*' || true)
  echo "  uat-bodytheory.admedia.com -> ${title:-no title found}"
}

main() {
  [ "$(id -un)" = devgroup ] || die "run as devgroup: sudo -u devgroup $0 $*"
  mkdir -p "$LOG_DIR"
  local mode=deploy branch=main
  case "${1:-}" in
    --status)  show_status; return 0 ;;
    --restart) mode=restart ;;
    -h|--help) sed -n '2,13p' "$0"; return 0 ;;
    "")        ;;
    -*)        die "unknown option $1" ;;
    *)         branch=$1 ;;
  esac

  if [ "$mode" = deploy ]; then
    say "Update repos ($branch)"
    for r in "${REPOS[@]}"; do update_repo "$r" "$branch"; done
    build_frontend
    build_service
  fi
  write_config
  stop_services
  start_services
  verify
  say "Deployed"; repo_summary
  echo
  echo "  Test: https://uat-<site>.admedia.com/   (logs: $LOG_DIR)"
}

main "$@"
exit
