#!/bin/bash
# Cariflex Full Backup Script
BACKUP_DIR="/home/eric/backups/cariflex/$(date +%Y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"

echo "=== Cariflex Full Backup $(date) ==="

# 1. PostgreSQL dump
echo "Backing up PostgreSQL..."
docker exec flexmeasures-db pg_dump -U flexmeasures flexmeasures | gzip > "$BACKUP_DIR/flexmeasures_db.sql.gz"

# 2. Redis dump
echo "Backing up Redis..."
docker exec flexmeasures-redis redis-cli BGSAVE
docker cp flexmeasures-redis:/data/dump.rdb "$BACKUP_DIR/redis_dump.rdb"

# 3. FM config and templates
echo "Backing up FM config..."
cp -r /home/eric/cariflex/templates "$BACKUP_DIR/"
cp -r /home/eric/cariflex/config "$BACKUP_DIR/" 2>/dev/null || true
cp /home/eric/flexmeasures/docker-compose.yml "$BACKUP_DIR/"
cp /home/eric/flexmeasures/docker-compose.openadr.yml "$BACKUP_DIR/"

# 4. OpenADR scripts
echo "Backing up OpenADR..."
cp -r /home/eric/flexmeasures/*.py "$BACKUP_DIR/"
cp /home/eric/flexmeasures/Dockerfile.openadr "$BACKUP_DIR/"
cp /home/eric/flexmeasures/start_ven.sh "$BACKUP_DIR/"

# 5. Grafana dashboards
echo "Backing up Grafana dashboards..."
curl -s -u admin:admin "http://localhost:3001/api/dashboards/uid/cariflex-ems-full" | python3 -c "
import json, sys
d = json.load(sys.stdin)
with open('$BACKUP_DIR/grafana_dashboard.json', 'w') as f:
    json.dump(d, f, indent=2)
print('Dashboard saved')
"

# 6. Docker container states
echo "Backing up container states..."
docker ps --format "table {{.Names}}\t{{.Image}}\t{{.Status}}" > "$BACKUP_DIR/containers.txt"
docker inspect openadr-vtn openadr-ven flexmeasures-server flexmeasures-db flexmeasures-redis 2>/dev/null > "$BACKUP_DIR/container_inspects.json"

# 7. Network config
echo "Backing up network config..."
docker network inspect openadr-internal 2>/dev/null > "$BACKUP_DIR/network_openadr.json"
docker network inspect traefik-public 2>/dev/null > "$BACKUP_DIR/network_traefik.json"

# 8. Compress
echo "Compressing..."
tar -czf "$BACKUP_DIR.tar.gz" -C "$(dirname $BACKUP_DIR)" "$(basename $BACKUP_DIR)"
rm -rf "$BACKUP_DIR"

echo "=== Backup complete: $BACKUP_DIR.tar.gz ==="
ls -lh "$BACKUP_DIR.tar.gz"
