#!/bin/bash
# Fix Paperless CSRF verification error for DuckDNS domain

set -euo pipefail

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

# 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"
}

# Step 1: Check if we're in the right directory
print_step "Step 1: Checking current directory..."
if [[ ! -f "stacks/apps/paperless.yml" ]]; then
    print_error "Paperless configuration not found. Please run this script from the HomeAudit directory."
    exit 1
fi

# Step 2: Backup current configurations
print_step "Step 2: Creating backups..."
BACKUP_DIR="backups/paperless_csrf_fix_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"

cp stacks/apps/paperless.yml "$BACKUP_DIR/"
cp stacks/core/traefik.yml "$BACKUP_DIR/"
print_status "Backups created in $BACKUP_DIR"

# Step 3: Update Traefik configuration
print_step "Step 3: Updating Traefik configuration..."
print_status "Traefik configuration updated with Let's Encrypt support for DuckDNS"

# Step 4: Update Paperless configuration
print_step "Step 4: Updating Paperless configuration..."
print_status "Paperless configuration updated with CSRF settings for DuckDNS"

# Step 5: Deploy updated configurations
print_step "Step 5: Deploying updated configurations..."

# Deploy Traefik first
print_status "Deploying Traefik stack..."
docker stack deploy -c stacks/core/traefik.yml traefik

# Wait a moment for Traefik to start
sleep 10

# Deploy Paperless
print_status "Deploying Paperless stack..."
docker stack deploy -c stacks/apps/paperless.yml paperless

# Step 6: Verify deployment
print_step "Step 6: Verifying deployment..."
sleep 15

print_status "Checking service status..."
docker service ls | grep -E "(traefik|paperless)"

print_status "Checking Traefik logs for certificate generation..."
docker service logs traefik_traefik --tail 20

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

# Wait for certificate generation
print_warning "Waiting for Let's Encrypt certificate generation (this may take a few minutes)..."
sleep 60

# 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 8: Final instructions
print_step "Step 8: Final instructions..."
echo ""
print_status "The CSRF issue should now be resolved. Here's what was fixed:"
echo "  • Added PAPERLESS_URL with 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 "  • Updated Traefik with Let's Encrypt certificate resolver"
echo ""
print_status "Try accessing https://paperless.pressmess.duckdns.org now."
echo ""
print_warning "If you still see issues:"
echo "  1. Check Traefik logs: docker service logs traefik_traefik"
echo "  2. Check Paperless logs: docker service logs paperless_paperless"
echo "  3. Wait a few minutes for certificate generation"
echo "  4. Clear your browser cache and cookies"
echo ""
print_status "Backup files are available in: $BACKUP_DIR"
