#!/bin/bash

# Linux Deployment Script for Al Mirag Poultry Management
# This script ensures proper setup and deployment on Linux servers

set -e  # Exit on any error

echo "🚀 Starting Linux deployment for Al Mirag Poultry Management..."

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

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

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

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

# Get the directory where the script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

print_status "Working directory: $SCRIPT_DIR"

# Check if running as root
if [[ $EUID -eq 0 ]]; then
   print_warning "This script is running as root. Consider running as a regular user."
fi

# 1. Check Python version
print_status "Checking Python version..."
if command -v python3 &> /dev/null; then
    PYTHON_VERSION=$(python3 --version 2>&1 | cut -d' ' -f2)
    print_success "Python 3 found: $PYTHON_VERSION"
    PYTHON_CMD="python3"
elif command -v python &> /dev/null; then
    PYTHON_VERSION=$(python --version 2>&1 | cut -d' ' -f2)
    if [[ $PYTHON_VERSION == 3.* ]]; then
        print_success "Python 3 found: $PYTHON_VERSION"
        PYTHON_CMD="python"
    else
        print_error "Python 3 is required. Found: $PYTHON_VERSION"
        exit 1
    fi
else
    print_error "Python 3 is not installed. Please install Python 3.7 or higher."
    exit 1
fi

# 2. Check pip
print_status "Checking pip..."
if command -v pip3 &> /dev/null; then
    PIP_CMD="pip3"
elif command -v pip &> /dev/null; then
    PIP_CMD="pip"
else
    print_error "pip is not installed. Please install pip."
    exit 1
fi

# 3. Install/upgrade dependencies
print_status "Installing Python dependencies..."
$PIP_CMD install --upgrade pip
$PIP_CMD install -r requirements.txt

# 4. Set proper file permissions
print_status "Setting file permissions..."
chmod 755 "$SCRIPT_DIR"
chmod 644 "$SCRIPT_DIR"/*.py
chmod 644 "$SCRIPT_DIR"/*.txt
chmod 644 "$SCRIPT_DIR"/*.md
chmod 644 "$SCRIPT_DIR"/.htaccess

# Set permissions for directories
chmod 755 "$SCRIPT_DIR"/static
chmod 755 "$SCRIPT_DIR"/templates
chmod 755 "$SCRIPT_DIR"/uploads
chmod 755 "$SCRIPT_DIR"/instance

# Set permissions for static files
find "$SCRIPT_DIR"/static -type f -exec chmod 644 {} \;
find "$SCRIPT_DIR"/static -type d -exec chmod 755 {} \;

# Set permissions for template files
find "$SCRIPT_DIR"/templates -type f -exec chmod 644 {} \;
find "$SCRIPT_DIR"/templates -type d -exec chmod 755 {} \;

# Set permissions for uploads directory (writable by web server)
chmod 777 "$SCRIPT_DIR"/uploads

# Set permissions for instance directory (database)
chmod 755 "$SCRIPT_DIR"/instance
if [ -f "$SCRIPT_DIR"/instance/poultry.db ]; then
    chmod 664 "$SCRIPT_DIR"/instance/poultry.db
fi

# 5. Create necessary directories
print_status "Creating necessary directories..."
mkdir -p "$SCRIPT_DIR"/logs
mkdir -p "$SCRIPT_DIR"/tmp
chmod 755 "$SCRIPT_DIR"/logs
chmod 755 "$SCRIPT_DIR"/tmp

# 6. Set up environment variables
print_status "Setting up environment variables..."
export FLASK_ENV=production
export PYTHONPATH="$SCRIPT_DIR"

# 7. Test database connection
print_status "Testing database connection..."
$PYTHON_CMD -c "
import sys
sys.path.insert(0, '$SCRIPT_DIR')
try:
    from app import app, db
    with app.app_context():
        db.create_all()
    print('Database connection successful')
except Exception as e:
    print(f'Database connection failed: {e}')
    sys.exit(1)
"

if [ $? -eq 0 ]; then
    print_success "Database connection test passed"
else
    print_error "Database connection test failed"
    exit 1
fi

# 8. Test WSGI application
print_status "Testing WSGI application..."
$PYTHON_CMD -c "
import sys
sys.path.insert(0, '$SCRIPT_DIR')
try:
    from passenger_wsgi import application
    print('WSGI application loaded successfully')
except Exception as e:
    print(f'WSGI application failed to load: {e}')
    sys.exit(1)
"

if [ $? -eq 0 ]; then
    print_success "WSGI application test passed"
else
    print_error "WSGI application test failed"
    exit 1
fi

# 9. Create systemd service file (optional)
print_status "Creating systemd service file..."
cat > "$SCRIPT_DIR"/poultry-app.service << EOF
[Unit]
Description=Al Mirag Poultry Management App
After=network.target

[Service]
Type=exec
User=www-data
Group=www-data
WorkingDirectory=$SCRIPT_DIR
Environment=FLASK_ENV=production
Environment=PYTHONPATH=$SCRIPT_DIR
ExecStart=/usr/bin/python3 $SCRIPT_DIR/app.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

print_success "Systemd service file created: $SCRIPT_DIR/poultry-app.service"

# 10. Create log rotation configuration
print_status "Creating log rotation configuration..."
cat > "$SCRIPT_DIR"/poultry-app.logrotate << EOF
$SCRIPT_DIR/logs/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 644 www-data www-data
    postrotate
        systemctl reload poultry-app || true
    endscript
}
EOF

print_success "Log rotation configuration created"

# 11. Create backup script
print_status "Creating backup script..."
cat > "$SCRIPT_DIR"/backup.sh << 'EOF'
#!/bin/bash
# Backup script for Al Mirag Poultry Management

BACKUP_DIR="/home/backups/poultry"
DATE=$(date +%Y%m%d_%H%M%S)
APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

mkdir -p "$BACKUP_DIR"

# Backup database
if [ -f "$APP_DIR/instance/poultry.db" ]; then
    cp "$APP_DIR/instance/poultry.db" "$BACKUP_DIR/poultry_backup_$DATE.db"
    echo "Database backed up to: $BACKUP_DIR/poultry_backup_$DATE.db"
fi

# Backup uploads
if [ -d "$APP_DIR/uploads" ]; then
    tar -czf "$BACKUP_DIR/uploads_backup_$DATE.tar.gz" -C "$APP_DIR" uploads/
    echo "Uploads backed up to: $BACKUP_DIR/uploads_backup_$DATE.tar.gz"
fi

# Keep only last 7 days of backups
find "$BACKUP_DIR" -name "*.db" -mtime +7 -delete
find "$BACKUP_DIR" -name "*.tar.gz" -mtime +7 -delete

echo "Backup completed successfully"
EOF

chmod +x "$SCRIPT_DIR"/backup.sh
print_success "Backup script created: $SCRIPT_DIR/backup.sh"

# 12. Create monitoring script
print_status "Creating monitoring script..."
cat > "$SCRIPT_DIR"/monitor.sh << 'EOF'
#!/bin/bash
# Monitoring script for Al Mirag Poultry Management

APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_FILE="$APP_DIR/logs/monitor.log"

# Function to log with timestamp
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

# Check if application is running
if pgrep -f "python.*app.py" > /dev/null; then
    log_message "Application is running"
else
    log_message "Application is not running - attempting restart"
    cd "$APP_DIR"
    nohup python3 app.py > logs/app.log 2>&1 &
    log_message "Application restart attempted"
fi

# Check disk space
DISK_USAGE=$(df "$APP_DIR" | tail -1 | awk '{print $5}' | sed 's/%//')
if [ "$DISK_USAGE" -gt 80 ]; then
    log_message "WARNING: Disk usage is ${DISK_USAGE}%"
fi

# Check database size
if [ -f "$APP_DIR/instance/poultry.db" ]; then
    DB_SIZE=$(du -h "$APP_DIR/instance/poultry.db" | cut -f1)
    log_message "Database size: $DB_SIZE"
fi
EOF

chmod +x "$SCRIPT_DIR"/monitor.sh
print_success "Monitoring script created: $SCRIPT_DIR/monitor.sh"

# 13. Final checks
print_status "Running final checks..."

# Check if all required files exist
REQUIRED_FILES=("app.py" "passenger_wsgi.py" "requirements.txt" "static/manifest.json" "templates/base.html")
for file in "${REQUIRED_FILES[@]}"; do
    if [ -f "$SCRIPT_DIR/$file" ]; then
        print_success "✓ $file exists"
    else
        print_error "✗ $file is missing"
        exit 1
    fi
done

# Check if all required directories exist
REQUIRED_DIRS=("static" "templates" "uploads" "instance")
for dir in "${REQUIRED_DIRS[@]}"; do
    if [ -d "$SCRIPT_DIR/$dir" ]; then
        print_success "✓ $dir directory exists"
    else
        print_error "✗ $dir directory is missing"
        exit 1
    fi
done

print_success "🎉 Linux deployment completed successfully!"
print_status "Next steps:"
echo "1. Copy the application files to your web server"
echo "2. Install dependencies: pip install -r requirements.txt"
echo "3. Set up your web server (Apache/Nginx) to use passenger_wsgi.py"
echo "4. Configure SSL certificate for HTTPS"
echo "5. Set up regular backups using: $SCRIPT_DIR/backup.sh"
echo "6. Set up monitoring using: $SCRIPT_DIR/monitor.sh"
echo ""
print_status "For web server configuration, see the generated .htaccess file"
print_status "For systemd service, copy poultry-app.service to /etc/systemd/system/"
print_status "For log rotation, copy poultry-app.logrotate to /etc/logrotate.d/"
