#!/bin/bash
# Quick fix script to verify and fix template issues on production
# Run this on the production server

echo "========================================================================"
echo "M-PESA TEMPLATE FIX SCRIPT"
echo "========================================================================"

# Set the base directory
BASE_DIR="/home/acbptxvs/public_html/branchbusinessadvance.co.ke"
TEMPLATES_DIR="$BASE_DIR/templates/payments"

echo ""
echo "Checking template directory: $TEMPLATES_DIR"

# Check if directory exists
if [ ! -d "$TEMPLATES_DIR" ]; then
    echo "ERROR: Templates directory does not exist!"
    echo "Creating directory..."
    mkdir -p "$TEMPLATES_DIR"
    chmod 755 "$TEMPLATES_DIR"
fi

echo ""
echo "Checking for required template files..."

# List of required templates
REQUIRED_TEMPLATES=(
    "callbacks.html"
    "transaction_detail.html"
    "reprocess_transaction.html"
    "my_payments.html"
    "dashboard.html"
    "transactions.html"
    "configuration.html"
    "test_payment.html"
)

MISSING=()

for template in "${REQUIRED_TEMPLATES[@]}"; do
    if [ -f "$TEMPLATES_DIR/$template" ]; then
        SIZE=$(stat -f%z "$TEMPLATES_DIR/$template" 2>/dev/null || stat -c%s "$TEMPLATES_DIR/$template" 2>/dev/null)
        PERMS=$(stat -f%A "$TEMPLATES_DIR/$template" 2>/dev/null || stat -c%a "$TEMPLATES_DIR/$template" 2>/dev/null)
        echo "✓ $template ($SIZE bytes, perms: $PERMS)"
        
        # Fix permissions if needed
        if [ "$PERMS" != "644" ]; then
            echo "  → Fixing permissions to 644"
            chmod 644 "$TEMPLATES_DIR/$template"
        fi
    else
        echo "✗ $template - MISSING"
        MISSING+=("$template")
    fi
done

echo ""
echo "========================================================================"

if [ ${#MISSING[@]} -eq 0 ]; then
    echo "✓ All templates present!"
    echo ""
    echo "Restarting application..."
    touch "$BASE_DIR/passenger_wsgi.py"
    echo "✓ Application restarted"
    echo ""
    echo "Try accessing: https://branchbusinessadvance.co.ke/payments/callbacks/"
else
    echo "✗ ${#MISSING[@]} template(s) missing:"
    for template in "${MISSING[@]}"; do
        echo "  - $template"
    done
    echo ""
    echo "ACTION REQUIRED:"
    echo "1. Upload missing templates to: $TEMPLATES_DIR/"
    echo "2. Run this script again to verify"
fi

echo "========================================================================"
