#!/bin/bash
# ============================================================
# Sekolahku — SSH Deploy Script untuk Domainesia
# Target: sekolahku.sosmartpro.com
# ============================================================
# Jalankan SETELAH:
#   1. Subdomain sudah dibuat di cPanel
#   2. Database sosmartp_sekolahku sudah ada dengan user sosmartp_admin
#   3. SSH in ke server
#   4. cd ke public_html/sekolahku.sosmartpro.com
# ============================================================

set -e  # exit on error
set -u  # treat unset variables as error

# ---- KONFIGURASI (sesuaikan kalau berbeda) ----
GIT_REPO="https://github.com/galihsidik86/sekolahku.git"
DB_HOST="localhost"
DB_NAME="sosmartp_sekolahku"
DB_USER="sosmartp_admin"
DB_PASS="19Feb2018."
APP_BASE_URL="https://sekolahku.sosmartpro.com/"
TARGET_DIR="$(pwd)"

# Warna output
G='\033[0;32m'   # green
Y='\033[1;33m'   # yellow
R='\033[0;31m'   # red
B='\033[0;34m'   # blue
NC='\033[0m'     # no color

log()  { echo -e "${G}[+]${NC} $*"; }
warn() { echo -e "${Y}[!]${NC} $*"; }
err()  { echo -e "${R}[x]${NC} $*"; }
hdr()  { echo -e "\n${B}========== $* ==========${NC}"; }

# ============================================================
# 1. PRE-FLIGHT CHECKS
# ============================================================
hdr "Pre-flight checks"

log "Lokasi deploy: $TARGET_DIR"

# Check PHP
if ! command -v php &> /dev/null; then
    err "PHP tidak ditemukan di PATH"; exit 1
fi
PHP_VER=$(php -r 'echo PHP_MAJOR_VERSION . "." . PHP_MINOR_VERSION;')
log "PHP version: $PHP_VER"
if [ "$(printf '%s\n' "8.1" "$PHP_VER" | sort -V | head -n1)" != "8.1" ]; then
    err "PHP 8.1+ required, ditemukan $PHP_VER"
    warn "Tip: di Domainesia, set PHP version via cPanel → Select PHP Version, lalu logout-login SSH"
    exit 1
fi

# Check PHP extensions (kecuali mysqli yang dicek terpisah karena ada
# 2 variant: mysqli vs nd_mysqli — biasanya conflicting di cPanel Selector)
REQUIRED_EXT=(intl mbstring curl json xml fileinfo)
for ext in "${REQUIRED_EXT[@]}"; do
    if ! php -m | grep -qi "^$ext$"; then
        err "PHP extension '$ext' tidak aktif"
        warn "Aktifkan via cPanel → Select PHP Version → Extensions"
        exit 1
    fi
done

# MySQL driver: terima mysqli (standar) ATAU nd_mysqli (native driver).
# Di CloudLinux/cPanel PHP Selector keduanya conflicting; cukup satu yang aktif.
if ! php -m | grep -qiE "^(nd_)?mysqli$"; then
    err "PHP extension 'mysqli' (atau 'nd_mysqli') tidak aktif"
    warn "Aktifkan SALAH SATU via cPanel → Select PHP Version → Extensions"
    warn "Catatan: warning 'nd_mysqli skipped as conflicting' itu OK — yang penting salah satu aktif"
    exit 1
fi
log "Semua PHP extensions tersedia"

# Check git
if ! command -v git &> /dev/null; then
    err "git tidak ditemukan"; exit 1
fi
log "git: $(git --version)"

# Check MySQL connection
if command -v mysql &> /dev/null; then
    if ! mysql -h "$DB_HOST" -u "$DB_USER" -p"$DB_PASS" -e "SELECT 1;" "$DB_NAME" &> /dev/null; then
        err "Gagal connect ke database $DB_NAME sebagai $DB_USER"
        warn "Verifikasi: cPanel → MySQL Databases → user ter-assign ke DB dengan ALL PRIVILEGES"
        exit 1
    fi
    log "Database connection OK"
else
    warn "mysql CLI tidak ada, skip DB check (akan di-verify saat migrate)"
fi

# Check write permission
if [ ! -w "$TARGET_DIR" ]; then
    err "Tidak bisa tulis ke $TARGET_DIR"; exit 1
fi

# ============================================================
# 2. CLONE / UPDATE REPOSITORY
# ============================================================
hdr "Clone / update repo"

if [ -d ".git" ]; then
    log "Repo sudah ada, pull update terbaru..."
    git pull --rebase || { err "git pull gagal"; exit 1; }
else
    # Direktori dianggap kosong kalau hanya berisi file yang acceptable:
    # - .well-known/  (Let's Encrypt SSL verification, jangan dihapus)
    # - deploy-ssh.sh (script ini sendiri)
    # - .htaccess     (kalau ada, akan ditimpa oleh repo)
    # - .ssh, .htpasswd, dll yang biasa muncul di /home shared hosting
    UNEXPECTED=$(ls -A . 2>/dev/null | grep -vE '^(\.well-known|deploy-ssh\.sh|\.htaccess|\.ssh|\.htpasswd|\.bash_logout|\.bashrc|\.bash_profile|\.profile)$' || true)
    if [ -n "$UNEXPECTED" ]; then
        err "Direktori berisi file tak terduga:"
        echo "$UNEXPECTED" | sed 's/^/    /'
        warn "Pindahkan/hapus file di atas dulu, atau pindah ke direktori kosong."
        exit 1
    fi

    # Backup file yang acceptable supaya tidak ke-overwrite oleh git clone
    BACKUP_DIR=$(mktemp -d /tmp/deploy-backup.XXXXXX)
    log "Backup .well-known/ dan deploy-ssh.sh sementara ke $BACKUP_DIR..."
    [ -e ".well-known" ]   && mv .well-known "$BACKUP_DIR/"
    [ -e "deploy-ssh.sh" ] && cp deploy-ssh.sh "$BACKUP_DIR/"

    log "Clone repo dari $GIT_REPO..."
    git clone "$GIT_REPO" . || { err "git clone gagal"; exit 1; }

    # Restore file yang di-backup
    log "Restore .well-known/..."
    [ -e "$BACKUP_DIR/.well-known" ]   && mv "$BACKUP_DIR/.well-known" .
    rm -rf "$BACKUP_DIR"
fi

# ============================================================
# 3. INSTALL COMPOSER DEPENDENCIES
# ============================================================
hdr "Install composer dependencies"

if [ -f "composer.phar" ]; then
    log "Pakai composer.phar bundled"
    php composer.phar install --no-dev --optimize-autoloader --no-interaction
elif command -v composer &> /dev/null; then
    log "Pakai composer system"
    composer install --no-dev --optimize-autoloader --no-interaction
else
    warn "composer tidak ada. Download composer.phar..."
    curl -sS https://getcomposer.org/installer | php
    php composer.phar install --no-dev --optimize-autoloader --no-interaction
fi
log "Dependencies installed"

# ============================================================
# 4. WRITE .env FILE
# ============================================================
hdr "Tulis file .env"

ENC_KEY=$(php -r "echo bin2hex(random_bytes(16));")
log "Encryption key generated: $ENC_KEY"

cat > .env << ENVEOF
#--------------------------------------------------------------------
# Sekolahku — Production Environment
# Generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)
#--------------------------------------------------------------------

CI_ENVIRONMENT = production

# APP
app.baseURL = '$APP_BASE_URL'
app.indexPage = ''
app.forceGlobalSecureRequests = true
app.CSPEnabled = false

# DATABASE
database.default.hostname = $DB_HOST
database.default.database = $DB_NAME
database.default.username = $DB_USER
database.default.password = $DB_PASS
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306
database.default.charset = utf8mb4
database.default.DBCollat = utf8mb4_general_ci

# ENCRYPTION
encryption.key = $ENC_KEY

# SESSION
session.driver = 'CodeIgniter\Session\Handlers\FileHandler'
session.savePath = null
session.cookieName = 'ci_session'
session.expiration = 7200

# COOKIE
cookie.secure = true
cookie.httponly = true
cookie.samesite = 'Lax'

# SECURITY
security.csrfProtection = 'cookie'
security.tokenRandomize = false
security.regenerate = true

# LOGGER
logger.threshold = 4
ENVEOF

chmod 600 .env
log "File .env tersimpan + permissions 600"

# ============================================================
# 5. PERMISSIONS & WRITABLE DIRECTORIES
# ============================================================
hdr "Set permissions writable directories"

mkdir -p writable/cache writable/logs writable/session writable/uploads writable/backups writable/debugbar
chmod -R 755 writable/
log "writable/ + subdirs OK"

# ============================================================
# 6. RUN MIGRATIONS
# ============================================================
hdr "Run database migrations"

php spark migrate --all || { err "Migration gagal"; exit 1; }
log "Migrations applied"

# ============================================================
# 7. RUN SEEDERS (opsional)
# ============================================================
hdr "Run database seeders"

read -p "Run DatabaseSeeder untuk data awal (admin + sample)? [y/N] " RUN_SEED
if [[ "$RUN_SEED" == "y" || "$RUN_SEED" == "Y" ]]; then
    php spark db:seed DatabaseSeeder || warn "Seeder gagal — bisa run manual nanti"
    log "Data awal ter-seed:"
    echo "    - admin / admin123"
    echo "    - guru1..6 / guru123"
    echo "    - siswa1..10 / siswa123"
    echo "    - ortu1..3 / ortu123 (wali murid)"
    echo "    - Sample data: 1 ekskul, 1 tagihan SPP, 1 pengumuman, 1 event kalender"
else
    log "Skip seed. Database kosong (struktur saja). Run manual via:"
    echo "    php spark db:seed AdminSeeder    # admin saja"
    echo "    php spark db:seed DatabaseSeeder # semua + sample data"
fi

# ============================================================
# 8. FINAL CHECKS
# ============================================================
hdr "Final checks"

# Verify key directories
for d in app system writable public vendor; do
    if [ ! -d "$d" ]; then
        err "Directory '$d' missing!"
        exit 1
    fi
done
log "Directory structure OK"

# Test PHP error
if php -l public/index.php > /dev/null 2>&1; then
    log "public/index.php syntax OK"
else
    err "public/index.php syntax error"
    exit 1
fi

# ============================================================
# DONE
# ============================================================
hdr "DEPLOYMENT SELESAI"

cat << 'DONEMSG'

✓ Aplikasi sudah ter-install di server.

LANGKAH SELANJUTNYA (via cPanel UI):
  1. Subdomains → ubah Document Root sekolahku ke:
     public_html/sekolahku.sosmartpro.com/public

  2. SSL/TLS Status → Run AutoSSL untuk sekolahku.sosmartpro.com
     (atau pakai Let's Encrypt → Issue)

  3. Buka https://sekolahku.sosmartpro.com → harus muncul halaman login
     (kalau halaman blank, force HTTPS via .htaccess di document root)

  4. Login dengan akun yang di-seed (admin/admin123) → GANTI PASSWORD!

  5. Lengkapi Profil Sekolah (untuk kop rapot, surat, slip SPP).

UPDATE APLIKASI di masa depan:
  cd public_html/sekolahku.sosmartpro.com
  bash deploy/deploy-ssh.sh
  # akan auto pull + composer install + migrate

CATATAN:
  - File .env permissions 600 (rw---- ----) — hanya owner yang bisa baca.
  - Untuk backup berkala, schedule cron job atau pakai menu Backup di app.
  - Log error PHP di writable/logs/ dan cPanel → Error Log.

DONEMSG
