#!/usr/bin/env bash
# Weekly Ansible automation runner
# Runs health_check and disk_usage_report across all active hosts.
# Installed as a cron job on homelab-vm — runs every Sunday at 06:00.
#
# Logs: /home/homelab/organized/repos/homelab/ansible/automation/logs/
# Alerts: sent via ntfy on any CRITICAL status (configured in health_check.yml)

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
AUTOMATION_DIR="$(dirname "$SCRIPT_DIR")"
LOG_DIR="$AUTOMATION_DIR/logs"
TIMESTAMP="$(date +%F_%H-%M-%S)"

mkdir -p "$LOG_DIR"

echo "=== Weekly Ansible run started: $TIMESTAMP ===" | tee "$LOG_DIR/weekly_${TIMESTAMP}.log"

# Pull latest repo changes first
cd "$(dirname "$(dirname "$AUTOMATION_DIR")")"
git pull --rebase --autostash >> "$LOG_DIR/weekly_${TIMESTAMP}.log" 2>&1 || true

cd "$AUTOMATION_DIR"

# Skip pi-5-kevin (offline)
LIMIT="active:!pi-5-kevin"

echo "--- Health check ---" | tee -a "$LOG_DIR/weekly_${TIMESTAMP}.log"
ansible-playbook playbooks/health_check.yml \
  -i hosts.ini \
  --limit "$LIMIT" \
  -e "ntfy_url=https://ntfy.vish.gg/homelab-alerts" \
  2>&1 | tee -a "$LOG_DIR/weekly_${TIMESTAMP}.log"

echo "--- Disk usage report ---" | tee -a "$LOG_DIR/weekly_${TIMESTAMP}.log"
ansible-playbook playbooks/disk_usage_report.yml \
  -i hosts.ini \
  --limit "$LIMIT" \
  2>&1 | tee -a "$LOG_DIR/weekly_${TIMESTAMP}.log"

echo "=== Weekly run complete: $(date +%F_%H-%M-%S) ===" | tee -a "$LOG_DIR/weekly_${TIMESTAMP}.log"

# Rotate logs — keep last 12 weeks
find "$LOG_DIR" -name "weekly_*.log" -mtime +84 -delete
