#!/bin/bash

# Production Deployment Script for Starting Line Productions LLC Website
# This script is used on the PRODUCTION server to deploy from git
#
# Usage: ./deploy-production.sh
#
# This should be run on the production server after content is pushed to the git repository

set -e

# Configuration
GIT_REPO="git@knownelement.com:StartingLineProductions.com/STLPWebsite.git"
GRAV_ROOT="/var/www/grav"  # Adjust to your production path
BACKUP_DIR="/var/backups/grav"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Helper functions
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if running as root or with sudo
if [ "$EUID" -ne 0 ]; then
    log_error "This script must be run as root or with sudo"
    exit 1
fi

# Create backup directory if it doesn't exist
if [ ! -d "$BACKUP_DIR" ]; then
    log_info "Creating backup directory: $BACKUP_DIR"
    mkdir -p "$BACKUP_DIR"
fi

# Create timestamped backup
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="grav_backup_$TIMESTAMP.tar.gz"

log_info "=== Production Deployment Script ==="
echo ""

# Backup current Grav installation
log_info "Creating backup of current installation..."
if [ -d "$GRAV_ROOT/user" ]; then
    tar -czf "$BACKUP_DIR/$BACKUP_FILE" -C "$GRAV_ROOT" user/ 2>/dev/null
    log_success "Backup created: $BACKUP_DIR/$BACKUP_FILE"
else
    log_warning "No user/ directory found (fresh install), skipping backup"
fi

# Pull latest changes from git
log_info "Pulling latest changes from git repository..."
cd "$GRAV_ROOT"

if [ ! -d ".git" ]; then
    log_warning "Git repository not initialized, cloning..."
    git clone "$GIT_REPO" "$GRAV_ROOT.tmp"
    mv "$GRAV_ROOT.tmp/." "$GRAV_ROOT/"
    rm -rf "$GRAV_ROOT.tmp"
else
    log_info "Updating existing repository..."
    git fetch origin
    git checkout main
    git pull origin main
fi

log_success "Repository updated"

# Set correct permissions
log_info "Setting correct permissions..."
chown -R www-data:www-data "$GRAV_ROOT/user"
find "$GRAV_ROOT/user" -type d -exec chmod 775 {} \;
find "$GRAV_ROOT/user" -type f -exec chmod 664 {} \;

# Clear Grav cache
log_info "Clearing Grav cache..."
rm -rf "$GRAV_ROOT/user/cache/*" 2>/dev/null || true
rm -rf "$GRAV_ROOT/user/logs/*" 2>/dev/null || true

log_success "Cache cleared"

# Install/update dependencies if needed (using Grav GPM)
log_info "Checking for plugin updates..."
cd "$GRAV_ROOT"
if [ -f "bin/gpm" ]; then
    php bin/gpm install -y 2>/dev/null || true
    log_info "Plugins checked"
else
    log_warning "GPM not found, skipping plugin checks"
fi

# Create .gitignore for production (if not exists)
if [ ! -f "$GRAV_ROOT/.gitignore" ]; then
    log_info "Creating .gitignore for production..."
    cat > "$GRAV_ROOT/.gitignore" << EOF
# Production-specific ignores
*.log
backup/
cache/
logs/
tmp/
EOF
fi

log_success "=== Deployment Complete ==="
echo ""
log_info "Next steps:"
echo "  1. Test the website in your browser"
echo "  2. Verify all pages load correctly"
echo "  3. Check for any errors in logs: $GRAV_ROOT/user/logs/"
echo ""
log_info "Backup location: $BACKUP_DIR/$BACKUP_FILE"
log_warning "Keep backups for at least 30 days"

# Optional: Restart web server (uncomment if needed)
# log_info "Restarting web server..."
# systemctl restart nginx
# systemctl restart php-fpm

echo ""
log_success "Starting Line Productions LLC website deployed successfully!"
