#!/usr/bin/env bash
# ==============================================================================
# Narada WhatsApp Marketing Platform - 1-Click AlmaLinux 9 Installer
# Official Meta WhatsApp Business Cloud API v21.0 & Laravel 13
# Configured for: DEWA Gram Udhyog Pvt Ltd (Bhiwani 127021 HR)
# ==============================================================================

set -e

DOMAIN="${1}"
DB_NAME="${2:-narada_db}"
DB_USER="${3:-narada_user}"
DB_PASS="${4:-NaradaSecurePass2026!}"

if [ -z "$DOMAIN" ]; then
    echo "======================================================================"
    echo " [ERROR] Domain name is required!"
    echo " Usage: sudo bash install-almalinux.sh <your-domain.com> [db_name] [db_user] [db_password]"
    echo " Example: sudo bash install-almalinux.sh portal.sdadigital.in"
    echo "======================================================================"
    exit 1
fi

echo "======================================================================"
echo " Starting Automated Installation for: $DOMAIN"
echo " OS: AlmaLinux 9 / RHEL 9 (PHP 8.3 + Nginx + MariaDB + Queue Worker)"
echo "======================================================================"

# 1. Update Packages & Enable Repositories
echo "[1/8] Installing EPEL, Remi PHP 8.3, Nginx & MariaDB..."
dnf update -y
dnf install -y epel-release curl wget git unzip zip tar policycoreutils-python-utils firewalld
dnf install -y https://rpms.remirepo.net/enterprise/remi-release-9.rpm
dnf module reset php -y
dnf module enable php:remi-8.3 -y

dnf install -y nginx mariadb-server certbot python3-certbot-nginx \
    php-fpm php-cli php-mysqlnd php-curl php-mbstring php-xml php-zip \
    php-bcmath php-intl php-gd php-opcache php-json

# 2. Start & Enable Services
echo "[2/8] Starting & Enabling System Services..."
systemctl enable --now nginx
systemctl enable --now php-fpm
systemctl enable --now mariadb
systemctl enable --now firewalld

# Configure Firewalld ports
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

# 3. Install Composer Globally if not present
if ! command -v composer &> /dev/null; then
    echo "[3/8] Installing Composer..."
    curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
fi

# 4. Setup MariaDB Database & User
echo "[4/8] Configuring MariaDB Database..."
mysql -e "CREATE DATABASE IF NOT EXISTS \`${DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
mysql -e "CREATE USER IF NOT EXISTS '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASS}';"
mysql -e "GRANT ALL PRIVILEGES ON \`${DB_NAME}\`.* TO '${DB_USER}'@'localhost';"
mysql -e "FLUSH PRIVILEGES;"

# 5. Setup Project Directory & Unpack
APP_DIR="/var/www/${DOMAIN}"
echo "[5/8] Deploying Application files to ${APP_DIR}..."
mkdir -p "${APP_DIR}"

# Copy files from current backend folder or extract zip if present
if [ -f "narada-backend-laravel.zip" ]; then
    unzip -o narada-backend-laravel.zip -d /tmp/narada_temp
    cp -r /tmp/narada_temp/backend/* "${APP_DIR}/"
    rm -rf /tmp/narada_temp
elif [ -d "backend" ]; then
    cp -r backend/* "${APP_DIR}/"
else
    cp -r ./* "${APP_DIR}/"
fi

cd "${APP_DIR}"

# 6. Configure .env & Laravel Application
echo "[6/8] Configuring Environment & Running Migrations..."
cat <<EOF > .env
APP_NAME=Narada
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_TIMEZONE=Asia/Kolkata
APP_URL=https://${DOMAIN}

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=${DB_NAME}
DB_USERNAME=${DB_USER}
DB_PASSWORD=${DB_PASS}

SESSION_DRIVER=database
QUEUE_CONNECTION=database

# Official Meta WhatsApp Business Cloud API v21.0
META_ACCESS_TOKEN=EAAG...
META_PHONE_NUMBER_ID=913349665192073
META_WABA_ID=1378746380406848
META_API_VERSION=v21.0
META_WEBHOOK_VERIFY_TOKEN=narada_wa_verify_secret_2026

# Business Profile
BUSINESS_NAME="DEWA Gram Udhyog Pvt Ltd"
BUSINESS_GSTIN="06AAJCD0975H1ZK"
BUSINESS_EMAIL="contact@sdadigital.in"
BUSINESS_PHONE="+919461321162"
BUSINESS_ADDRESS="Gali No 4, Uttam Nagar Loharu Road, Bhiwani 127021 HR"
EOF

# Install dependencies, generate key, migrate & seed
composer install --no-dev --optimize-autoloader
php artisan key:generate --force
php artisan migrate --seed --force
php artisan config:cache
php artisan route:cache
php artisan view:cache

# 7. Configure Permissions & SELinux for AlmaLinux 9
echo "[7/8] Configuring SELinux Contexts & Nginx Permissions..."
sed -i 's/user = apache/user = nginx/g' /etc/php-fpm.d/www.conf
sed -i 's/group = apache/group = nginx/g' /etc/php-fpm.d/www.conf
sed -i 's/;listen.owner = nobody/listen.owner = nginx/g' /etc/php-fpm.d/www.conf
sed -i 's/;listen.group = nobody/listen.group = nginx/g' /etc/php-fpm.d/www.conf
systemctl restart php-fpm

chown -R nginx:nginx "${APP_DIR}"
chmod -R 775 "${APP_DIR}/storage" "${APP_DIR}/bootstrap/cache"

# SELinux rules
setsebool -P httpd_can_network_connect 1
semanage fcontext -a -t httpd_sys_rw_content_t "${APP_DIR}/storage(/.*)?" || true
semanage fcontext -a -t httpd_sys_rw_content_t "${APP_DIR}/bootstrap/cache(/.*)?" || true
restorecon -Rv "${APP_DIR}" || true

# 8. Configure Nginx VirtualHost
echo "[8/8] Creating Nginx Server Block..."
cat <<EOF > /etc/nginx/conf.d/${DOMAIN}.conf
server {
    listen 80;
    server_name ${DOMAIN};
    root ${APP_DIR}/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php index.html;
    charset utf-8;

    location / {
        try_files \$uri \$uri/ /index.php?\$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/run/php-fpm/www.sock;
        fastcgi_param SCRIPT_FILENAME \$realpath_root\$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_hide_header X-Powered-By;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
EOF

nginx -t
systemctl restart nginx

# 9. Setup Background Queue Worker Systemd Service
cat <<EOF > /etc/systemd/system/narada-worker.service
[Unit]
Description=Narada WhatsApp Marketing Background Worker
After=network.target mariadb.service

[Service]
User=nginx
Group=nginx
Restart=always
ExecStart=/usr/bin/php ${APP_DIR}/artisan queue:work database --sleep=3 --tries=3 --max-time=3600
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now narada-worker

echo "======================================================================"
echo " INSTALLATION COMPLETE!"
echo "======================================================================"
echo " 1. Portal Selector URL: http://${DOMAIN}/"
echo " 2. Consumer Workspace:  http://${DOMAIN}/consumer/login"
echo " 3. Admin Operations:    http://${DOMAIN}/admin/login"
echo " 4. Super Admin Console: http://${DOMAIN}/superadmin/login"
echo " 5. Meta Webhook URL:    http://${DOMAIN}/webhooks/meta"
echo ""
echo " To activate Free SSL (HTTPS), run:"
echo " certbot --nginx -d ${DOMAIN}"
echo "======================================================================"
