#!/bin/bash

# cPanel Rollover Status Update Script
# ===================================
# This script updates rolled over loan statuses on your production server

echo "🎯 cPanel Rollover Status Update Script"
echo "========================================"
echo "This script will update rolled over loan statuses"
echo "to follow the new pattern (active instead of approved)"
echo "========================================"

# Check if Python is available
if ! command -v python3 &> /dev/null; then
    if ! command -v python &> /dev/null; then
        echo "❌ Python is not installed or not in PATH"
        exit 1
    else
        PYTHON_CMD="python"
    fi
else
    PYTHON_CMD="python3"
fi

echo "✅ Using Python command: $PYTHON_CMD"

# Check if the script exists
if [ ! -f "cpanel_update_rollover_status.py" ]; then
    echo "❌ cpanel_update_rollover_status.py not found in current directory"
    echo "Please make sure the script is in the same directory as your Django project"
    exit 1
fi

# Create backup before running
echo "📦 Creating backup of database..."
BACKUP_FILE="rollover_backup_$(date +%Y%m%d_%H%M%S).sql"
if command -v mysqldump &> /dev/null; then
    # Try to get database info from Django settings
    DB_NAME=$(python -c "
import os, sys, django
sys.path.append('.')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()
from django.conf import settings
print(settings.DATABASES['default']['NAME'])
" 2>/dev/null)
    
    if [ ! -z "$DB_NAME" ]; then
        mysqldump "$DB_NAME" > "$BACKUP_FILE" 2>/dev/null
        if [ $? -eq 0 ]; then
            echo "✅ Database backup created: $BACKUP_FILE"
        else
            echo "⚠️  Could not create database backup (continuing anyway)"
        fi
    else
        echo "⚠️  Could not determine database name (continuing anyway)"
    fi
else
    echo "⚠️  mysqldump not available (continuing anyway)"
fi

# Run the Python script
echo "🚀 Running rollover status update..."
$PYTHON_CMD cpanel_update_rollover_status.py

# Check exit status
if [ $? -eq 0 ]; then
    echo ""
    echo "🎉 Script completed successfully!"
    echo "All rolled over loans now follow the new status pattern."
    echo ""
    echo "📋 Next steps:"
    echo "1. Check your Django admin to verify the changes"
    echo "2. Test the rollover functionality"
    echo "3. Keep the backup file ($BACKUP_FILE) for safety"
else
    echo ""
    echo "❌ Script failed!"
    echo "Please check the error messages above and try again."
    echo "If you have a backup, you can restore it if needed."
    exit 1
fi
