#!/bin/bash
# Fix settings.py on server: ensure django.contrib.contenttypes in INSTALLED_APPS
# Run on server: cd /var/www/html/loadboard && bash deploy/fix-settings-apache.sh

SETTINGS="/var/www/html/loadboard/Loadboard/settings.py"
BACKUP="${SETTINGS}.bak.$(date +%s)"

if [ ! -f "$SETTINGS" ]; then
    echo "Error: $SETTINGS not found"
    exit 1
fi

# Backup
cp "$SETTINGS" "$BACKUP"
echo "Backed up to $BACKUP"

# Check if contenttypes already present
if grep -q "django.contrib.contenttypes" "$SETTINGS"; then
    echo "django.contrib.contenttypes already in INSTALLED_APPS"
    echo "Checking full INSTALLED_APPS..."
    grep -A 20 "INSTALLED_APPS" "$SETTINGS" | head -25
    exit 0
fi

# Create fixed INSTALLED_APPS block
python3 << 'PYFIX'
path = "/var/www/html/loadboard/Loadboard/settings.py"
with open(path) as f:
    content = f.read()

# Replace INSTALLED_APPS with correct version
old = "INSTALLED_APPS = ["
new = """INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
    'accounts',
    'core',
    'api',
    'widget_tweaks',
]"""

# Find and replace - handle various formats
import re
# Match INSTALLED_APPS = [ ... ] (multiline)
pattern = r"INSTALLED_APPS\s*=\s*\[[^\]]*\]"
if re.search(pattern, content, re.DOTALL):
    content = re.sub(pattern, new, content, count=1, flags=re.DOTALL)
    with open(path, "w") as f:
        f.write(content)
    print("Fixed INSTALLED_APPS")
else:
    print("Could not find INSTALLED_APPS block. Please replace settings.py manually.")
PYFIX

echo "Restart Apache: sudo systemctl restart apache2"
