#!/bin/bash
# EXIM ERP Setup Script for Ubuntu 24.04/26.04
# Run as root or with sudo

set -e

echo "=========================================="
echo "EXIM ERP Setup Script"
echo "=========================================="

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

print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

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

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

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

# 1. System updates
print_status "Updating system packages..."
apt update && apt upgrade -y

# 2. Install essential packages
print_status "Installing essential packages..."
apt install -y software-properties-common apt-transport-https ca-certificates curl gnupg lsb-release unzip git

# 3. Install PHP 8.3
print_status "Installing PHP 8.3..."
add-apt-repository ppa:ondrej/php -y
apt update
apt install -y php8.3 php8.3-fpm php8.3-mysql php8.3-redis php8.3-mbstring php8.3-xml php8.3-curl php8.3-gd php8.3-zip php8.3-bcmath php8.3-intl php8.3-imagick php8.3-readline php8.3-dom

# 4. Install MySQL 8
print_status "Installing MySQL 8..."
apt install -y mysql-server
systemctl enable mysql
systemctl start mysql

# 5. Install Redis
print_status "Installing Redis..."
apt install -y redis-server
systemctl enable redis-server
systemctl start redis-server

# 6. Install Nginx
print_status "Installing Nginx..."
apt install -y nginx
systemctl enable nginx

# 7. Install Supervisor
print_status "Installing Supervisor..."
apt install -y supervisor
systemctl enable supervisor

# 8. Install Composer
print_status "Installing Composer..."
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
chmod +x /usr/local/bin/composer

# 9. Create database and user
print_status "Setting up MySQL database..."
mysql -e "CREATE DATABASE IF NOT EXISTS exim_erp CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
mysql -e "CREATE USER IF NOT EXISTS 'exim_erp_user'@'localhost' IDENTIFIED BY 'EximErp@2025';"
mysql -e "GRANT ALL PRIVILEGES ON exim_erp.* TO 'exim_erp_user'@'localhost';"
mysql -e "FLUSH PRIVILEGES;"

# 10. Create application directory
print_status "Setting up application directory..."
mkdir -p /var/www/html/exim-erp

# 11. Set permissions
print_status "Setting permissions..."
chown -R www-data:www-data /var/www/html/exim-erp
chmod -R 755 /var/www/html/exim-erp
chmod -R 775 /var/www/html/exim-erp/storage 2>/dev/null || true
chmod -R 775 /var/www/html/exim-erp/bootstrap/cache 2>/dev/null || true

# 12. Configure Nginx
print_status "Configuring Nginx..."
cp /var/www/html/exim-erp/deployment/nginx/exim-erp.conf /etc/nginx/sites-available/exim-erp
ln -sf /etc/nginx/sites-available/exim-erp /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

# 13. Configure PHP-FPM
print_status "Configuring PHP-FPM..."
cp /var/www/html/exim-erp/deployment/php/99-exim-erp.ini /etc/php/8.3/fpm/conf.d/99-exim-erp.ini
cp /var/www/html/exim-erp/deployment/php/php-fpm-pool.conf /etc/php/8.3/fpm/pool.d/exim-erp.conf

# 14. Configure Supervisor
print_status "Configuring Supervisor..."
cp /var/www/html/exim-erp/deployment/supervisor/*.conf /etc/supervisor/conf.d/

# 15. Create log directories
print_status "Creating log directories..."
mkdir -p /var/log/supervisor
mkdir -p /var/log/nginx
mkdir -p /var/log/php8.3-fpm

# 16. SSL setup (self-signed for initial setup)
print_status "Creating self-signed SSL certificate..."
mkdir -p /etc/ssl/certs /etc/ssl/private
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
    -keyout /etc/ssl/private/exim-erp.key \
    -out /etc/ssl/certs/exim-erp.crt \
    -subj "/C=US/ST=State/L=City/O=EXIM ERP/CN=localhost"

# 17. Laravel setup
print_status "Setting up Laravel application..."
cd /var/www/html/exim-erp

if [ -f .env.example ]; then
    cp .env.example .env
fi

if [ -f composer.json ]; then
    composer install --no-dev --optimize-autoloader
    php artisan key:generate
    php artisan migrate --force
    php artisan config:cache
    php artisan route:cache
    php artisan view:cache
    php artisan optimize
fi

# 18. Setup cron jobs
print_status "Setting up cron jobs..."
cp /var/www/html/exim-erp/deployment/cron/exim-erp /etc/cron.d/exim-erp
chmod 644 /etc/cron.d/exim-erp

# 19. Start services
print_status "Starting services..."
systemctl restart php8.3-fpm
systemctl restart nginx
systemctl restart redis-server
systemctl restart mysql
supervisorctl reread
supervisorctl update

# 20. Verify installation
print_status "Verifying installation..."
systemctl is-active --quiet php8.3-fpm && print_status "PHP-FPM: Running" || print_error "PHP-FPM: Not running"
systemctl is-active --quiet nginx && print_status "Nginx: Running" || print_error "Nginx: Not running"
systemctl is-active --quiet mysql && print_status "MySQL: Running" || print_error "MySQL: Not running"
systemctl is-active --quiet redis-server && print_status "Redis: Running" || print_error "Redis: Not running"

echo ""
echo "=========================================="
echo -e "${GREEN}EXIM ERP setup complete!${NC}"
echo "=========================================="
echo ""
echo "Next steps:"
echo "1. Install Let's Encrypt SSL: certbot --nginx -d your-domain.com"
echo "2. Update .env file with your configuration"
echo "3. Access the application at https://your-domain.com"
echo ""
echo "Default login:"
echo "Email: admin@exim-erp.com"
echo "Password: password"
echo ""
