#!/usr/bin/env bash

# Resolve the PM2 executable from an explicitly attested runtime.  The staging
# deploy runs in a non-interactive SSH shell, so its PATH must not be assumed to
# match the account/runtime used by the server-owned deploy-staging.sh.

phase1_pm2_error() {
  printf 'Phase 1 PM2 resolver: %s\n' "$1" >&2
  return 1
}

phase1_stat_owner_mode() {
  local path=$1
  if stat -Lc '%u %a' "$path" >/dev/null 2>&1; then
    stat -Lc '%u %a' "$path"
  else
    stat -f '%u %Lp' "$path"
  fi
}

phase1_path_chain_is_trusted() {
  local path=$1
  local canonical=""
  local current=""
  local owner=""
  local mode=""
  local world_digit=""
  local current_uid=""
  local -a paths=()

  [[ "$path" == /* ]] || return 1
  canonical=$(readlink -f "$path" 2>/dev/null || true)
  [[ "$canonical" == /* ]] || return 1
  current_uid=$(id -u)
  paths=("$path" "$canonical")
  for current in "${paths[@]}"; do
    while true; do
      read -r owner mode < <(phase1_stat_owner_mode "$current") || return 1
      if [[ "$owner" != "$current_uid" ]] && [[ "$owner" != "0" ]]; then
        return 1
      fi
      world_digit=${mode: -1}
      if (( (10#$world_digit & 2) != 0 )); then
        return 1
      fi
      [[ "$current" == "/" ]] && break
      current=$(dirname "$current")
    done
  done
}

phase1_resolve_pm2_from_proc() {
  local proc_root=${1:-/proc}
  local current_uid=""
  local effective_uid=""
  local key=""
  local real_uid=""
  local saved_uid=""
  local filesystem_uid=""
  local command_line=""
  local environment_entry=""
  local supervisor_path=""
  local node_executable=""
  local candidate=""
  local canonical_candidate=""
  local path_entry=""
  local process_dir=""
  local -a daemon_processes=()
  local -a runtime_candidates=()
  local -a supervisor_path_entries=()
  local -a unique_candidates=()

  [[ -d "$proc_root" ]] || return 1
  current_uid=$(id -u)
  for process_dir in "$proc_root"/[0-9]*; do
    [[ -d "$process_dir" ]] || continue
    effective_uid=""
    while IFS=$' \t' read -r key real_uid effective_uid saved_uid filesystem_uid; do
      if [[ "$key" == "Uid:" ]]; then
        break
      fi
      effective_uid=""
    done < "$process_dir/status" 2>/dev/null || true
    [[ "$effective_uid" == "$current_uid" ]] || continue
    command_line=$(tr '\0' ' ' < "$process_dir/cmdline" 2>/dev/null || true)
    if [[ "$command_line" == *PM2*God*Daemon* ]]; then
      daemon_processes+=("$process_dir")
    fi
  done

  if [[ ${#daemon_processes[@]} -eq 0 ]]; then
    return 1
  fi
  if [[ ${#daemon_processes[@]} -ne 1 ]]; then
    phase1_pm2_error "expected one current-user PM2 God daemon; found ${#daemon_processes[@]}"
    return 2
  fi

  node_executable=$(readlink -f "${daemon_processes[0]}/exe" 2>/dev/null || true)
  if [[ "$node_executable" == /* ]] && [[ -x "$node_executable" ]] && \
    phase1_path_chain_is_trusted "$node_executable"; then
    runtime_candidates+=("$(dirname "$node_executable")/pm2")
  fi
  while IFS= read -r -d '' environment_entry; do
    if [[ "$environment_entry" == PATH=* ]]; then
      supervisor_path=${environment_entry#PATH=}
      break
    fi
  done < "${daemon_processes[0]}/environ" 2>/dev/null || true
  if [[ -n "$supervisor_path" ]]; then
    IFS=: read -r -a supervisor_path_entries <<< "$supervisor_path"
    for path_entry in "${supervisor_path_entries[@]}"; do
      [[ "$path_entry" == /* ]] || continue
      runtime_candidates+=("$path_entry/pm2")
    done
  fi

  for candidate in "${runtime_candidates[@]}"; do
    [[ -x "$candidate" ]] || continue
    phase1_path_chain_is_trusted "$candidate" || continue
    canonical_candidate=$(readlink -f "$candidate" 2>/dev/null || true)
    [[ "$canonical_candidate" == /* ]] || continue
    "$canonical_candidate" --version >/dev/null 2>&1 || continue
    if [[ " ${unique_candidates[*]} " != *" $canonical_candidate "* ]]; then
      unique_candidates+=("$canonical_candidate")
    fi
  done
  if [[ ${#unique_candidates[@]} -eq 0 ]]; then
    return 1
  fi
  if [[ ${#unique_candidates[@]} -ne 1 ]]; then
    phase1_pm2_error "PM2 daemon runtime attested ${#unique_candidates[@]} executable candidates"
    return 2
  fi
  PHASE1_PROC_PM2_BIN=${unique_candidates[0]}
  export PHASE1_PROC_PM2_BIN
}

phase1_attest_no_publisher_processes() {
  local proc_root=${1:-/proc}
  local current_uid=""
  local effective_uid=""
  local key=""
  local real_uid=""
  local saved_uid=""
  local filesystem_uid=""
  local command_line=""
  local process_dir=""
  local publisher_count=0

  [[ -d "$proc_root" ]] || {
    phase1_pm2_error "process filesystem is unavailable for publisher attestation"
    return 1
  }
  current_uid=$(id -u)
  for process_dir in "$proc_root"/[0-9]*; do
    [[ -d "$process_dir" ]] || continue
    effective_uid=""
    while IFS=$' \t' read -r key real_uid effective_uid saved_uid filesystem_uid; do
      if [[ "$key" == "Uid:" ]]; then
        break
      fi
      effective_uid=""
    done < "$process_dir/status" 2>/dev/null || true
    [[ "$effective_uid" == "$current_uid" ]] || continue
    command_line=$(tr '\0' ' ' < "$process_dir/cmdline" 2>/dev/null || true)
    if [[ "$command_line" == *manage.py\ publish_resource_booking_outbox* ]]; then
      publisher_count=$((publisher_count + 1))
    fi
  done
  if [[ $publisher_count -ne 0 ]]; then
    phase1_pm2_error "default-off attestation found $publisher_count publisher process(es)"
    return 1
  fi
}

phase1_resolve_pm2() {
  local candidate=""
  local proc_status=0
  local runtime_bootstrap=""
  local restore_nounset="false"

  if [[ -n "${TT_PHASE1_PM2_BIN:-}" ]]; then
    candidate=$TT_PHASE1_PM2_BIN
  else
    candidate=$(type -P pm2 2>/dev/null || true)
    if [[ -z "$candidate" ]]; then
      if phase1_resolve_pm2_from_proc /proc; then
        candidate=$PHASE1_PROC_PM2_BIN
      else
        proc_status=$?
        if [[ $proc_status -eq 2 ]]; then
          return 1
        fi
      fi
    fi
    if [[ -z "$candidate" ]]; then
      runtime_bootstrap=${TT_PHASE1_RUNTIME_BOOTSTRAP:-"${HOME:?HOME is required}/.nvm/nvm.sh"}
      if [[ "$runtime_bootstrap" != /* ]] || [[ ! -f "$runtime_bootstrap" ]] || \
        [[ ! -r "$runtime_bootstrap" ]] || [[ ! -O "$runtime_bootstrap" ]]; then
        phase1_pm2_error "runtime bootstrap must be an absolute, regular, readable, owner-controlled file"
        return 1
      fi
      # shellcheck disable=SC1090 -- exact protected path is checked immediately above.
      if [[ $- == *u* ]]; then
        restore_nounset="true"
        set +u
      fi
      source "$runtime_bootstrap"
      if type nvm >/dev/null 2>&1; then
        nvm use default --silent >/dev/null 2>&1 || true
      fi
      if [[ "$restore_nounset" == "true" ]]; then
        set -u
      fi
      candidate=$(type -P pm2 2>/dev/null || true)
    fi
  fi

  if [[ -z "$candidate" ]] || [[ "$candidate" != /* ]] || [[ ! -x "$candidate" ]]; then
    phase1_pm2_error "no absolute executable PM2 was resolved from the attested runtime"
    return 1
  fi
  if ! "$candidate" --version >/dev/null 2>&1; then
    phase1_pm2_error "resolved PM2 executable failed its version probe"
    return 1
  fi

  PHASE1_PM2_BIN=$candidate
  export PHASE1_PM2_BIN
}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
  set -euo pipefail
  phase1_resolve_pm2
  printf '%s\n' "$PHASE1_PM2_BIN"
fi
