#!/bin/bash
# ==========================================================
# Script Deployment Otomatis (GitHub -> aaPanel)
# Proyek: YOUR_PROJECT_NAME
# ==========================================

# --- 1. KONFIGURASI PATH & NOTIFIKASI ---
PROJECT_PATH="/www/wwwroot/your-domain.com"
PHP_BIN="/www/server/php/83/bin/php"
NODE_BIN="/www/server/nodejs/v24.12.0/bin/node"

# Fix Enviroment for Composer & Git
export HOME=/root
export COMPOSER_HOME=/root/.composer
git config --global --add safe.directory $PROJECT_PATH

# Telegram Config
BOT_TOKEN="YOUR_BOT_TOKEN"
CHAT_ID="YOUR_CHAT_ID"

function send_telegram() {
    local message=$1
    curl -s -X POST "https://api.telegram.org/bot$BOT_TOKEN/sendMessage" \
        -d "chat_id=$CHAT_ID" \
        -d "text=$message" \
        -d "parse_mode=Markdown" > /dev/null
}

echo "==== STARTING DEPLOYMENT: $(date) ===="
send_telegram "🚀 *Deployment Started* for your-domain.com on $(date)"

cd $PROJECT_PATH || { 
    send_telegram "❌ *Deployment Failed*: Project path not found!"; 
    exit 1; 
}

# --- 2. UPDATE KODE DARI GITHUB ---
echo "[1/6] Fetching latest code from GitHub..."
git fetch --all
git reset --hard origin/main

# --- 3. MANAJEMEN DEPENDENSI (PHP) ---
echo "[2/6] Updating PHP dependencies (Composer)..."
# Mencari lokasi composer secara dinamis
if [ -f "/usr/local/bin/composer" ]; then
    COMPOSER_PATH="/usr/local/bin/composer"
elif [ -f "/usr/bin/composer" ]; then
    COMPOSER_PATH="/usr/bin/composer"
else
    COMPOSER_PATH=$(which composer)
fi

$PHP_BIN $COMPOSER_PATH install --no-dev --optimize-autoloader --no-interaction || $PHP_BIN $COMPOSER_PATH update --no-dev --optimize-autoloader --no-interaction

# --- 4. DATABASE MIGRATION ---
echo "[3/6] Running database migrations..."
# Cek apakah vendor ada sebelum jalankan artisan
if [ ! -d "vendor" ]; then
    echo "ERROR: Folder vendor tidak ditemukan. Composer install gagal."
    send_telegram "❌ *Deployment Failed*: Vendor folder missing (Composer error)!"
    exit 1
fi
$PHP_BIN artisan migrate --force


# --- 5. BUILD FRONTEND ASSETS ---
echo "[4/6] Installing & Building assets (Vite)..."
export PATH=$PATH:$(dirname $NODE_BIN)
npm install
npm run build

# --- 6. OPTIMASI LARAVEL ---
echo "[5/6] Running optimizations..."
$PHP_BIN artisan optimize
$PHP_BIN artisan view:cache
$PHP_BIN artisan storage:link --force

# --- 7. PERMISSION & CLEANUP ---
echo "[6/6] Fixing permissions..."
chown -R www:www $PROJECT_PATH
chmod -R 775 $PROJECT_PATH/storage $PROJECT_PATH/bootstrap/cache

echo "==== DEPLOYMENT COMPLETED SUCCESSFULLY ===="
send_telegram "✅ *Deployment Success*: your-domain.com is now updated!"
