#!/usr/bin/env bash
# Runs INSIDE VMID 5000 (explorer). Keeps Blockscout API and nginx up; optional safe disk prune.
# Install with: bash scripts/install-explorer-cron.sh
# Cron: every 5 min health check + recover; daily safe disk prune.

set -euo pipefail

LOG="${EXPLORER_MAINTAIN_LOG:-/var/log/explorer-maintain.log}"
BLOCKSCOUT_DIR="${BLOCKSCOUT_DIR:-/opt/blockscout}"

log() { echo "$(date -Iseconds) $*" >> "$LOG" 2>/dev/null || true; }

# 1) Ensure PostgreSQL is running
docker start blockscout-postgres 2>/dev/null || true

# 2) Blockscout API health: if not 200, restart or start container
CODE=$(curl -sS -o /dev/null -w "%{http_code}" --connect-timeout 5 http://127.0.0.1:4000/api/v2/stats 2>/dev/null || echo "000")
if [ "$CODE" != "200" ]; then
    CONTAINER=$(docker ps -a --format '{{.Names}}' 2>/dev/null | grep -E "blockscout" | grep -v postgres | head -1 | tr -d '\n\r' || true)
    if [ -n "$CONTAINER" ]; then
        log "API not 200 (got $CODE). Restarting container: $CONTAINER"
        docker restart "$CONTAINER" 2>>"$LOG" || true
        sleep 15
    elif [ -f "$BLOCKSCOUT_DIR/docker-compose.yml" ]; then
        log "API not 200 (got $CODE). Starting Blockscout from $BLOCKSCOUT_DIR"
        (cd "$BLOCKSCOUT_DIR" && docker-compose up -d blockscout 2>>"$LOG") || true
        sleep 20
    fi
fi

# 3) Nginx: ensure running
NGINX=$(systemctl is-active nginx 2>/dev/null || echo "inactive")
if [ "$NGINX" != "active" ]; then
    log "Nginx not active. Starting nginx."
    systemctl start nginx 2>>"$LOG" || true
fi

# 4) Safe disk prune (only if env RUN_PRUNE=1 or first run on Sunday 3am - use cron for daily)
# Do NOT prune containers (would remove stopped Blockscout). Prune only unused images and build cache.
if [ "${RUN_PRUNE:-0}" = "1" ]; then
    USED_PCT=$(df / --output=pcent 2>/dev/null | tail -1 | tr -d ' %' || echo "0")
    if [ -n "$USED_PCT" ] && [ "$USED_PCT" -ge 90 ]; then
        log "Disk usage ${USED_PCT}%. Running safe prune (images + build cache only)."
        docker image prune -f 2>>"$LOG" || true
        docker builder prune -f 2>>"$LOG" || true
    fi
fi

exit 0
