#!/bin/bash
# Restic backup script for Hördle deployment
# Creates a backup snapshot with tags and handles errors gracefully

set -e

if [ -f "$HOME/.restic-env" ]; then
    # shellcheck source=/dev/null
    . "$HOME/.restic-env"
fi

echo "💾 Creating Restic backup..."

if ! command -v restic >/dev/null 2>&1; then
    echo "⚠️  restic not found in PATH, skipping Restic backup"
    exit 0
fi

# Check required environment variables
if [ -z "$RESTIC_PASSWORD" ]; then
    echo "⚠️  RESTIC_PASSWORD not set, skipping Restic backup"
    exit 0
fi

if [ -z "$RESTIC_AUTH_USER" ] || [ -z "$RESTIC_AUTH_PASSWORD" ]; then
    echo "⚠️  RESTIC_AUTH_USER or RESTIC_AUTH_PASSWORD not set, skipping Restic backup"
    exit 0
fi

# Build repository URL
RESTIC_REPO="rest:https://${RESTIC_AUTH_USER}:${RESTIC_AUTH_PASSWORD}@restic.elpatron.me/"

# Get current commit hash for tagging
CURRENT_COMMIT_SHORT="$(git rev-parse --short HEAD 2>/dev/null || echo 'unknown')"
CURRENT_DATE="$(date +%Y-%m-%d)"

# Export password for restic
export RESTIC_PASSWORD

# Check if repository exists, initialize if not
if ! restic -r "$RESTIC_REPO" snapshots >/dev/null 2>&1; then
    echo "   Initializing Restic repository..."
    if ! restic -r "$RESTIC_REPO" init >/dev/null 2>&1; then
        echo "⚠️  Failed to initialize Restic repository, skipping backup"
        exit 0
    fi
fi

# Create backup with tags
# Backup important directories: backups, config files, but exclude node_modules, .git, etc.
echo "   Creating Restic snapshot..."
RESTIC_EXIT_CODE=0
restic -r "$RESTIC_REPO" backup \
    --tag deployment \
    --tag hoerdle \
    --tag "date:${CURRENT_DATE}" \
    --tag "commit:${CURRENT_COMMIT_SHORT}" \
    --exclude='.git' \
    --exclude='node_modules' \
    --exclude='.next' \
    --exclude='*.log' \
    ./backups \
    ./data \
    ./public/uploads \
    docker-compose.yml \
    .env \
    package.json \
    prisma/schema.prisma \
    prisma/migrations \
    scripts/ || RESTIC_EXIT_CODE=$?

if [ $RESTIC_EXIT_CODE -eq 0 ]; then
    echo "✅ Restic backup completed successfully"
    exit 0
elif [ $RESTIC_EXIT_CODE -eq 3 ]; then
    echo "⚠️  Restic backup completed with warnings (some files could not be read), continuing..."
    exit 0
else
    echo "⚠️  Restic backup failed (exit code: $RESTIC_EXIT_CODE), continuing deployment..."
    exit 0
fi

