#!/bin/bash
# Cariflex - Snapshot script
# Creates a backup of all modified files before any change
# Usage: bash snapshot.sh [description]

set -e

SNAPSHOT_DIR="/home/eric/cariflex/snapshots/$(date +%Y%m%d_%H%M%S)"
DESCRIPTION="${1:-manual}"
mkdir -p "$SNAPSHOT_DIR"

echo "=== Cariflex Snapshot: $DESCRIPTION ==="
echo "Directory: $SNAPSHOT_DIR"

# 1. Backup FM templates
echo "Backing up FM templates..."
docker cp flexmeasures-server:/app/flexmeasures/ui/templates/admin/login_user.html "$SNAPSHOT_DIR/login_user.html" 2>/dev/null || true
docker cp flexmeasures-server:/app/flexmeasures/ui/templates/includes/navbar.html "$SNAPSHOT_DIR/navbar.html" 2>/dev/null || true
docker cp flexmeasures-server:/app/flexmeasures/ui/templates/includes/footer.html "$SNAPSHOT_DIR/footer.html" 2>/dev/null || true
docker cp flexmeasures-server:/app/flexmeasures/ui/templates/includes/teaser.html "$SNAPSHOT_DIR/teaser.html" 2>/dev/null || true

# 2. Backup FM config
echo "Backing up FM config..."
docker cp flexmeasures-server:/app/instance/flexmeasures.cfg "$SNAPSHOT_DIR/flexmeasures.cfg" 2>/dev/null || true

# 3. Backup FM static images
echo "Backing up FM static images..."
docker cp flexmeasures-server:/app/flexmeasures/ui/static/images/cariflex-logo.jpg "$SNAPSHOT_DIR/cariflex-logo.jpg" 2>/dev/null || true
docker cp flexmeasures-server:/app/flexmeasures/ui/static/images/flexmeasures-preview.jpg "$SNAPSHOT_DIR/flexmeasures-preview.jpg" 2>/dev/null || true

# 4. Backup docker-compose files
echo "Backing up docker-compose files..."
cp /home/eric/flexmeasures/docker-compose.yml "$SNAPSHOT_DIR/docker-compose.yml" 2>/dev/null || true

# 5. Save snapshot info
echo "Description: $DESCRIPTION" > "$SNAPSHOT_DIR/info.txt"
echo "Date: $(date)" >> "$SNAPSHOT_DIR/info.txt"
echo "Host: $(hostname)" >> "$SNAPSHOT_DIR/info.txt"

# 6. Git commit the snapshot
cd /home/eric/cariflex
git add snapshots/
git commit -m "Snapshot: $DESCRIPTION" --allow-empty 2>/dev/null || true
git push origin master 2>/dev/null || true

echo "=== Snapshot complete ==="
echo "Files backed up to: $SNAPSHOT_DIR"
ls -la "$SNAPSHOT_DIR"
