#!/bin/bash

# Paperless-ngx Production Setup Script
# Run this script after deploying the updated Docker Compose configuration

set -e

echo "🔧 Setting up Paperless-ngx in production..."

# Check if we're in the right directory
if [ ! -f "docker-compose.yml" ]; then
    echo "❌ Error: docker-compose.yml not found. Please run this script from /opt/stiftung"
    exit 1
fi

# Generate a random secret key for Paperless
echo "🔑 Generating Paperless secret key..."
PAPERLESS_SECRET=$(openssl rand -base64 50 | tr -d "=+/" | cut -c1-50)

echo "📝 Please add this to your app/.env file:"
echo "PAPERLESS_SECRET_KEY=$PAPERLESS_SECRET"
echo ""
echo "Press Enter to continue after you've added the secret key to your .env file..."
read -r

# Restart containers to pick up new environment variables
echo "� Restarting containers..."
docker-compose down
docker-compose up -d

# Wait for database to be ready
echo "⏳ Waiting for database to be ready..."
sleep 60

# Wait for Paperless to be ready
echo "⏳ Waiting for Paperless to initialize..."
sleep 30

# Check if Paperless is running
echo "🔍 Checking Paperless container status..."
docker-compose ps paperless

# Run Paperless migrations
echo "📊 Running Paperless migrations..."
docker-compose exec -T paperless python3 manage.py migrate --no-input

# Create Paperless superuser non-interactively
echo "👤 Creating Paperless superuser..."
docker-compose exec -T paperless python3 manage.py shell -c "
from django.contrib.auth import get_user_model
User = get_user_model()
if not User.objects.filter(username='admin').exists():
    User.objects.create_superuser('admin', 'admin@vhtv-stiftung.de', 'admin123')
    print('Admin user created successfully')
else:
    print('Admin user already exists')
"

echo ""
echo "✅ Paperless-ngx setup complete!"
echo ""
echo "📚 Login details:"
echo "URL: https://vhtv-stiftung.de/paperless/"
echo "Username: admin"
echo "Password: admin123"
echo ""
echo "⚠️  IMPORTANT: Change the admin password immediately after first login!"
echo ""
echo "� Next steps:"
echo "1. Visit https://vhtv-stiftung.de/paperless/ and change the admin password"
echo "2. Go to https://vhtv-stiftung.de/paperless/admin/"
echo "3. Navigate to Authentication and Authorization > Tokens" 
echo "4. Create a new token for the admin user"
echo "5. Add the token to your app/.env file as PAPERLESS_API_TOKEN"
echo "6. Restart containers: docker-compose restart"
