#!/bin/bash

# BondaCare Deployment Script
# This script helps deploy or update the BondaCare application

set -e  # Exit on error

echo "=========================================="
echo "  BondaCare Deployment Script"
echo "=========================================="
echo ""

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

# Function to print colored output
print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

print_info() {
    echo -e "${YELLOW}ℹ $1${NC}"
}

# Check if running as root
if [ "$EUID" -eq 0 ]; then 
    print_error "Please do not run this script as root"
    exit 1
fi

# Detect deployment type
echo "Select deployment type:"
echo "1) Initial Deployment (First time)"
echo "2) Update Deployment (Pull latest changes)"
echo "3) Quick Update (No npm build)"
read -p "Enter choice [1-3]: " DEPLOY_TYPE

# Get application path
read -p "Enter application path [/var/www/bondacare]: " APP_PATH
APP_PATH=${APP_PATH:-/var/www/bondacare}

if [ ! -d "$APP_PATH" ]; then
    print_error "Directory $APP_PATH does not exist!"
    exit 1
fi

cd "$APP_PATH"
print_success "Changed to directory: $APP_PATH"

# Initial Deployment
if [ "$DEPLOY_TYPE" == "1" ]; then
    print_info "Starting Initial Deployment..."
    
    # Check if .env exists
    if [ ! -f ".env" ]; then
        print_info "Creating .env file from .env.example"
        cp .env.example .env
        print_success ".env file created"
        print_error "IMPORTANT: Please edit .env file with your database credentials!"
        read -p "Press enter after editing .env file..."
    fi
    
    # Install Composer dependencies
    print_info "Installing Composer dependencies..."
    composer install --optimize-autoloader --no-dev
    print_success "Composer dependencies installed"
    
    # Install NPM dependencies
    print_info "Installing NPM dependencies..."
    npm install
    print_success "NPM dependencies installed"
    
    # Build assets
    print_info "Building assets..."
    npm run build
    print_success "Assets built"
    
    # Generate application key
    print_info "Generating application key..."
    php artisan key:generate
    print_success "Application key generated"
    
    # Create storage link
    print_info "Creating storage link..."
    php artisan storage:link
    print_success "Storage link created"
    
    # Run migrations
    read -p "Run database migrations? (y/n): " RUN_MIGRATIONS
    if [ "$RUN_MIGRATIONS" == "y" ]; then
        print_info "Running migrations..."
        php artisan migrate --force
        print_success "Migrations completed"
        
        read -p "Run database seeders? (y/n): " RUN_SEEDERS
        if [ "$RUN_SEEDERS" == "y" ]; then
            print_info "Running seeders..."
            php artisan db:seed --force
            print_success "Seeders completed"
        fi
    fi
    
    # Set permissions
    print_info "Setting permissions..."
    sudo chown -R www-data:www-data "$APP_PATH"
    sudo chmod -R 755 "$APP_PATH"
    sudo chmod -R 775 "$APP_PATH/storage"
    sudo chmod -R 775 "$APP_PATH/bootstrap/cache"
    print_success "Permissions set"
    
    # Cache configuration
    print_info "Caching configuration..."
    php artisan config:cache
    php artisan route:cache
    php artisan view:cache
    print_success "Configuration cached"
    
    print_success "Initial deployment completed!"

# Update Deployment
elif [ "$DEPLOY_TYPE" == "2" ]; then
    print_info "Starting Update Deployment..."
    
    # Put application in maintenance mode
    print_info "Enabling maintenance mode..."
    php artisan down
    print_success "Maintenance mode enabled"
    
    # Pull latest changes
    print_info "Pulling latest changes from Git..."
    git pull origin main
    print_success "Latest changes pulled"
    
    # Install/Update Composer dependencies
    print_info "Updating Composer dependencies..."
    composer install --optimize-autoloader --no-dev
    print_success "Composer dependencies updated"
    
    # Install/Update NPM dependencies
    print_info "Updating NPM dependencies..."
    npm install
    print_success "NPM dependencies updated"
    
    # Build assets
    print_info "Building assets..."
    npm run build
    print_success "Assets built"
    
    # Run migrations
    print_info "Running migrations..."
    php artisan migrate --force
    print_success "Migrations completed"
    
    # Clear and cache
    print_info "Clearing and caching..."
    php artisan config:clear
    php artisan cache:clear
    php artisan view:clear
    php artisan route:clear
    php artisan config:cache
    php artisan route:cache
    php artisan view:cache
    print_success "Cache cleared and rebuilt"
    
    # Bring application back online
    print_info "Disabling maintenance mode..."
    php artisan up
    print_success "Application is back online"
    
    print_success "Update deployment completed!"

# Quick Update
elif [ "$DEPLOY_TYPE" == "3" ]; then
    print_info "Starting Quick Update..."
    
    # Put application in maintenance mode
    print_info "Enabling maintenance mode..."
    php artisan down
    print_success "Maintenance mode enabled"
    
    # Pull latest changes
    print_info "Pulling latest changes from Git..."
    git pull origin main
    print_success "Latest changes pulled"
    
    # Install/Update Composer dependencies
    print_info "Updating Composer dependencies..."
    composer install --optimize-autoloader --no-dev
    print_success "Composer dependencies updated"
    
    # Run migrations
    print_info "Running migrations..."
    php artisan migrate --force
    print_success "Migrations completed"
    
    # Clear and cache
    print_info "Clearing and caching..."
    php artisan config:clear
    php artisan cache:clear
    php artisan view:clear
    php artisan route:clear
    php artisan config:cache
    php artisan route:cache
    php artisan view:cache
    print_success "Cache cleared and rebuilt"
    
    # Bring application back online
    print_info "Disabling maintenance mode..."
    php artisan up
    print_success "Application is back online"
    
    print_success "Quick update completed!"

else
    print_error "Invalid choice!"
    exit 1
fi

echo ""
echo "=========================================="
print_success "Deployment Completed Successfully!"
echo "=========================================="
echo ""
print_info "Next steps:"
echo "  1. Visit your website to verify it's working"
echo "  2. Check logs: tail -f storage/logs/laravel.log"
echo "  3. Monitor web server logs"
echo ""

