#!/bin/bash

LOCK="/tmp/wiia-recovery.lock"
LOG="/tmp/wiia-recovery.log"
NOW=$(date "+%F %T")

HEALTH_URL="https://ia.wiia.pro/health/ready"
RESTART_URL="https://ia.wiia.pro/restart-node.php"
WAKE_URL="https://ia.wiia.pro/wake"

TOKEN="O2yX"

DEVICES=(
  "5219971223441"
  "5216625143800"
)

# Evita que se encimen varios cron al mismo tiempo
if [ -f "$LOCK" ]; then
  AGE=$(( $(date +%s) - $(cat "$LOCK" 2>/dev/null || echo 0) ))

  if [ "$AGE" -lt 90 ]; then
    echo "[$NOW] recovery skipped, lock active age=${AGE}s" >> "$LOG"
    exit 0
  fi
fi

date +%s > "$LOCK"

STATUS=$(timeout 6s curl -s -o /dev/null -w "%{http_code}" --connect-timeout 3 --max-time 5 "$HEALTH_URL" 2>&1)
EXIT=$?

if [ "$EXIT" != "0" ] || [ "$STATUS" != "200" ]; then
  echo "[$NOW] health failed exit=$EXIT status=$STATUS, restarting node..." >> "$LOG"

  RESTART=$(timeout 10s curl -sS --connect-timeout 3 --max-time 8 -X POST "$RESTART_URL" -H "X-Restart-Token: $TOKEN" 2>&1)
  echo "[$NOW] restart response=$RESTART" >> "$LOG"

  # Espera a que Node levante
  sleep 8

  # Reactiva dispositivos escalonado
  for DEVICE in "${DEVICES[@]}"; do
    WAKE=$(timeout 6s curl -sS --connect-timeout 3 --max-time 5 -X POST "$WAKE_URL" -H "X-Wake-Token: $TOKEN" -d "token_device=$DEVICE" 2>&1)
    echo "[$NOW] wake device=$DEVICE response=$WAKE" >> "$LOG"
    sleep 4
  done

  # Segunda revisión después del wake
  sleep 5

  STATUS2=$(timeout 6s curl -s -o /dev/null -w "%{http_code}" --connect-timeout 3 --max-time 5 "$HEALTH_URL" 2>&1)
  EXIT2=$?

  echo "[$NOW] post-restart health exit=$EXIT2 status=$STATUS2" >> "$LOG"
else
  echo "[$NOW] health ok status=$STATUS" >> "$LOG"
fi

rm -f "$LOCK"