#!/usr/bin/env bash
# Free disk space in VMID 5000 (explorer/Blockscout). Run when you see "no space left on device".
# Usage: from repo root, EXPLORER_VM_HOST=root@192.168.11.12 bash scripts/free-disk-vmid5000.sh
#    or on Proxmox host: bash scripts/free-disk-vmid5000.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
[ -f "$REPO_ROOT/../.env" ] && source "$REPO_ROOT/../.env" 2>/dev/null || true
VMID="${EXPLORER_VMID:-5000}"
EXPLORER_NODE="${EXPLORER_VM_HOST:-${PROXMOX_R630_02:-192.168.11.12}}"
if [[ "$EXPLORER_NODE" == *"@"* ]]; then SSH_TARGET="$EXPLORER_NODE"; else SSH_TARGET="root@$EXPLORER_NODE"; fi

if ! command -v pct &>/dev/null || ! pct list 2>/dev/null | grep -q "^$VMID "; then
    if [ -n "${EXPLORER_VM_HOST:-}" ] || [ -n "${PROXMOX_R630_02:-}" ]; then
        scp -o StrictHostKeyChecking=no -o ConnectTimeout=10 "$SCRIPT_DIR/free-disk-vmid5000.sh" "$SSH_TARGET:/tmp/free-disk-vmid5000.sh" 2>/dev/null || true
        ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 "$SSH_TARGET" "EXPLORER_VM_HOST= bash /tmp/free-disk-vmid5000.sh"
        exit $?
    else
        echo "Run on Proxmox host or set EXPLORER_VM_HOST=root@<node-ip>"
        exit 1
    fi
fi

EXEC_PREFIX="pct exec $VMID --"

echo "=============================================="
echo "Free disk space in VMID $VMID"
echo "=============================================="
echo ""
echo "=== Disk usage before ==="
$EXEC_PREFIX df -h /
echo ""
$EXEC_PREFIX docker system df 2>/dev/null || true
echo ""
echo "=== Journal vacuum (keep 1d, max 100M) ==="
$EXEC_PREFIX journalctl --vacuum-time=1d 2>/dev/null || true
$EXEC_PREFIX journalctl --vacuum-size=100M 2>/dev/null || true
echo ""
echo "=== Old backups (keep last 2) ==="
$EXEC_PREFIX sh -c 'ls -t /var/www/html/index.html.backup.* 2>/dev/null | tail -n +3 | xargs -r rm -f' 2>/dev/null || true
$EXEC_PREFIX sh -c 'ls -t /etc/nginx/sites-available/blockscout.backup.* 2>/dev/null | tail -n +3 | xargs -r rm -f' 2>/dev/null || true
echo ""
echo "=== Truncate syslog + logrotate ==="
$EXEC_PREFIX sh -c ': > /var/log/syslog 2>/dev/null; logrotate -f /etc/logrotate.conf 2>/dev/null' || true
echo ""
echo "=== Pruning unused Docker data (safe: no container prune) ==="
# Do NOT use 'docker system prune' - it removes stopped containers (e.g. Blockscout)
$EXEC_PREFIX docker image prune -f 2>/dev/null || true
$EXEC_PREFIX docker builder prune -f 2>/dev/null || true
echo ""
echo "=== Disk usage after ==="
$EXEC_PREFIX df -h /
echo ""
echo "=============================================="
echo "Done. Rerun fix-502 script: EXPLORER_VM_HOST=root@192.168.11.12 bash scripts/fix-502-blockscout.sh"
echo "=============================================="
