#!/usr/bin/env bash
set -euo pipefail

safe_segment_re='[a-z0-9][a-z0-9-]{0,62}'
allowed_path_re="^/var/www/camps/${safe_segment_re}/${safe_segment_re}(/${safe_segment_re})?/?$"
camp_deploy_command="${CAMP_DEPLOY_COMMAND:-/usr/local/bin/camp-deploy}"
camp_admin_command="${CAMP_ADMIN_COMMAND:-/usr/local/bin/camp-admin}"

known_camp() {
  "$camp_deploy_command" --is-known-camp "$1" >/dev/null 2>&1
}

split_ssh_command() {
  python3 - "$1" <<'PY'
import shlex
import sys

for part in shlex.split(sys.argv[1]):
    print(part)
PY
}

if [[ -z "${SSH_ORIGINAL_COMMAND:-}" ]]; then
  cat <<'MSG'
SuperBrain Camp Deploy
This account is restricted to camp project uploads.

Allowed:
  rsync upload to /var/www/camps/<camp>/<username>/<project>/
  camp-deploy <camp> <username> [project]
  echo OK
MSG
  exit 0
fi

cmd="$SSH_ORIGINAL_COMMAND"

if [[ "$cmd" == "echo OK" || "$cmd" == "echo ok" ]]; then
  echo "OK"
  exit 0
fi

if [[ "$cmd" == rsync\ --server* ]]; then
  parts=()
  while IFS= read -r part; do
    parts+=("$part")
  done < <(split_ssh_command "$cmd")
  target_index=$((${#parts[@]} - 1))
  target="${parts[$target_index]:-}"

  if [[ -z "$target" || "$target" == *".."* || "$target" == *"//"* ]]; then
    echo "camp-deploy-shell: unsafe rsync path" >&2
    exit 1
  fi
  if [[ ! "$target" =~ $allowed_path_re ]]; then
    echo "camp-deploy-shell: rsync is only allowed under /var/www/camps/<camp>/<username>/<project>/" >&2
    exit 1
  fi
  camp_part="${target#/var/www/camps/}"
  camp_part="${camp_part%%/*}"
  if ! known_camp "$camp_part"; then
    echo "camp-deploy-shell: unknown camp: $camp_part" >&2
    exit 1
  fi
  for i in "${!parts[@]}"; do
    if [[ "$i" -ne "$target_index" && "${parts[$i]}" == /* ]]; then
      echo "camp-deploy-shell: rsync destination must be the only absolute path" >&2
      exit 1
    fi
  done
  if command -v rsync >/dev/null 2>&1; then
    exec "${parts[@]}"
  fi
  echo "camp-deploy-shell: rsync not installed" >&2
  exit 1
fi

parts=()
while IFS= read -r part; do
  parts+=("$part")
done < <(split_ssh_command "$cmd")
if [[ "${parts[0]:-}" == "camp-deploy" && "${#parts[@]}" -ge 3 && "${#parts[@]}" -le 4 ]]; then
  exec "$camp_deploy_command" "${parts[@]:1}"
fi

if [[ "${parts[0]:-}" == "camp-admin" && "${#parts[@]}" -ge 2 ]]; then
  exec "$camp_admin_command" "${parts[@]:1}"
fi

if [[ "$cmd" == "camp-list" || "$cmd" == "list" ]]; then
  find /var/www/camps -mindepth 2 -maxdepth 3 -type d 2>/dev/null | sort
  exit 0
fi

echo "camp-deploy-shell: command not allowed" >&2
exit 1
