#!/usr/bin/env bash
set -u

project_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
pid_file="$project_root/outputs/logs/ecmwf_recovery_1989-03.pid"
log_file="$project_root/outputs/logs/ecmwf_recovery_1989-03.log"
manifest="$project_root/data/ecmwf/recovery/1989-03-instantaneous/recovery_manifest.json"
supervisor_pid_file="$project_root/outputs/logs/ecmwf_recovery_supervisor.pid"
supervisor_log="$project_root/outputs/logs/ecmwf_recovery_supervisor.log"

printf 'Recovery supervisor:\n'
if [[ -s "$supervisor_pid_file" ]]; then
  supervisor_pid="$(<"$supervisor_pid_file")"
  ps -o pid,ppid,pgid,sid,etime,stat,%cpu,%mem,args -p "$supervisor_pid" 2>/dev/null || true
else
  printf 'PID file absent\n'
fi

printf '\nRecovery process:\n'
if [[ -s "$pid_file" ]]; then
  recovery_pid="$(<"$pid_file")"
  ps -o pid,ppid,pgid,sid,etime,stat,%cpu,%mem,args -p "$recovery_pid" 2>/dev/null || true
else
  printf 'PID file absent\n'
fi

printf '\nManifest summary:\n'
if [[ -s "$manifest" ]]; then
  jq '{status, initial_month, initial_chunk_leads, single_step_variables,
       chunks_total:(.chunks|length),
       chunks_downloaded:([.chunks[]|select(.status=="downloaded")]|length),
       chunks_existing:([.chunks[]|select(.status=="validated_existing")]|length),
       chunks_split:([.chunks[]|select(.status=="split")]|length),
       chunks_error:([.chunks[]|select(.status=="error")]|length),
       updated_utc, validation}' "$manifest"
else
  printf 'Manifest absent\n'
fi

printf '\nRecent supervisor log:\n'
tail -n 12 "$supervisor_log" 2>/dev/null || true

printf '\nRecent recovery log:\n'
tail -n 25 "$log_file" 2>/dev/null || true
