#!/bin/bash
# Fix Paperless CSRF verification error for Caddy reverse proxy

set -euo pipefail

echo "🔧 Fixing Paperless CSRF verification error with Caddy..."

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# Configuration
SURFACE_HOST="jon@192.168.50.254"
OMV800_HOST="root@192.168.50.229"
CADDY_CONFIG_PATH="/etc/caddy/Caddyfile"
BACKUP_DIR="backups/paperless_caddy_csrf_fix_$(date +%Y%m%d_%H%M%S)"

# Step 1: Create backup directory
print_step "Step 1: Creating backups..."
mkdir -p "$BACKUP_DIR"

# Step 2: Backup current configurations
print_step "Step 2: Backing up current configurations..."
cp paperless_fix_compose.yml "$BACKUP_DIR/"
cp corrected_caddyfile.txt "$BACKUP_DIR/"

# Step 3: Update Caddy configuration on surface
print_step "Step 3: Updating Caddy configuration on surface..."
print_status "Copying updated Caddyfile to surface..."

# Copy the updated Caddyfile to surface
scp corrected_caddyfile.txt "$SURFACE_HOST:/tmp/Caddyfile.paperless"

# SSH to surface and update Caddy configuration
ssh "$SURFACE_HOST" << 'EOF'
    # Backup current Caddyfile
    sudo cp /etc/caddy/Caddyfile /etc/caddy/Caddyfile.backup.$(date +%Y%m%d_%H%M%S)
    
    # Replace with updated configuration
    sudo cp /tmp/Caddyfile.paperless /etc/caddy/Caddyfile
    
    # Test Caddy configuration
    sudo caddy validate --config /etc/caddy/Caddyfile
    
    # Reload Caddy
    sudo systemctl reload caddy
    
    # Check Caddy status
    sudo systemctl status caddy --no-pager -l
EOF

print_status "✅ Caddy configuration updated and reloaded"

# Step 4: Update Paperless configuration on OMV800
print_step "Step 4: Updating Paperless configuration on OMV800..."
print_status "Copying updated Paperless configuration to OMV800..."

# Copy the updated Paperless configuration to OMV800
scp paperless_fix_compose.yml "$OMV800_HOST:/tmp/paperless_fix_compose.yml"

# SSH to OMV800 and restart Paperless
ssh "$OMV800_HOST" << 'EOF'
    # Navigate to Paperless directory (adjust path as needed)
    cd /opt/paperless || cd /home/paperless || cd /root/paperless
    
    # Backup current configuration
    if [ -f docker-compose.yml ]; then
        cp docker-compose.yml docker-compose.yml.backup.$(date +%Y%m%d_%H%M%S)
    fi
    
    # Copy updated configuration
    cp /tmp/paperless_fix_compose.yml docker-compose.yml
    
    # Stop current Paperless stack
    docker-compose down
    
    # Start with updated configuration
    docker-compose up -d
    
    # Check service status
    docker-compose ps
    
    # Check logs for any errors
    docker-compose logs webserver --tail 20
EOF

print_status "✅ Paperless configuration updated and restarted"

# Step 5: Wait for services to start
print_step "Step 5: Waiting for services to start..."
sleep 30

# Step 6: Test the connection
print_step "Step 6: Testing Paperless access..."
print_status "Testing https://paperless.pressmess.duckdns.org..."

# Test the connection
if curl -s -o /dev/null -w "%{http_code}" https://paperless.pressmess.duckdns.org | grep -q "200\|302"; then
    print_status "✅ Paperless is accessible!"
else
    print_warning "⚠️  Paperless may still be starting up. Please wait a few more minutes and try again."
fi

# Step 7: Final instructions
print_step "Step 7: Final instructions..."
echo ""
print_status "The CSRF issue should now be resolved. Here's what was fixed:"
echo "  • Updated Paperless environment variables for CSRF support"
echo "  • Added proper reverse proxy headers in Caddy configuration"
echo "  • Updated PAPERLESS_URL to use your DuckDNS domain"
echo "  • Added PAPERLESS_CSRF_TRUSTED_ORIGINS for CSRF validation"
echo "  • Added PAPERLESS_ALLOWED_HOSTS for security"
echo "  • Added reverse proxy headers configuration"
echo ""
print_status "Try accessing https://paperless.pressmess.duckdns.org now."
echo ""
print_warning "If you still see issues:"
echo "  1. Check Caddy logs: ssh $SURFACE_HOST 'sudo journalctl -u caddy -f'"
echo "  2. Check Paperless logs: ssh $OMV800_HOST 'docker-compose logs webserver'"
echo "  3. Wait a few minutes for services to fully start"
echo "  4. Clear your browser cache and cookies"
echo ""
print_status "Backup files are available in: $BACKUP_DIR"
