# MC-ExamGO — Panduan Instalasi

```
    __  ___  ______         ______ _  __  ___    __  ___     ______  ____
   /  |/  / / ____/        / ____/| |/ / /   |  /  |/  /    / ____/ / __ \
  / /|_/ / / /    ______  / __/   |   / / /| | / /|_/ /    / / __  / / / /
 / /  / / / /___ /_____/ / /___  /   | / ___ |/ /  / /    / /_/ / / /_/ /
/_/  /_/  \____/        /_____/ /_/|_|/_/  |_/_/  /_/     \____/  \____/

                        MC-ExamGO Server v1.0.0
         Computer Based Test — Standalone Binary (No PHP, No Node.js)
```

---

## Isi Paket

```
MC-ExamGo-Win/
|-- mc-exam-go-windows-amd64-v1.0.0.exe    <- Server utama
|-- mc-exam-go-migrate.exe                 <- Tool migrasi database (jalankan SEKALI)
|-- .env                                   <- File konfigurasi (WAJIB diisi)
|-- uploads/                               <- Folder penyimpanan file upload
|-- logs/                                  <- Folder log aplikasi
`-- README.md                              <- Panduan ini
```

> Catatan: Semua file di atas harus berada dalam SATU FOLDER yang sama.
> PHP, Node.js, dan XAMPP TIDAK dibutuhkan. Binary ini sudah self-contained.

---

## Persyaratan Sistem

| Komponen   | Minimum                   | Rekomendasi               |
| ---------- | ------------------------- | ------------------------- |
| RAM        | 512 MB                    | 1 GB+                     |
| Storage    | 500 MB                    | 2 GB+                     |
| OS         | Windows 10 / Ubuntu 20.04 | Windows 11 / Ubuntu 22.04 |
| PostgreSQL | v14+                      | v16+                      |

---

---

## [A] INSTALASI DI WINDOWS (Lokal / Sekolah)

### Langkah 1 — Install PostgreSQL

1. Download PostgreSQL dari https://www.postgresql.org/download/windows/
2. Install dengan pengaturan default, catat username dan password
3. Buka pgAdmin 4, buat database baru:
   - Klik kanan pada Databases -> Create -> Database
   - Isi nama: mc_examgo (atau sesuai keinginan)
   - Klik Save

### Langkah 2 — Konfigurasi .env

Buka file .env dengan Notepad, sesuaikan bagian ini:

    DB_HOST=localhost
    DB_PORT=5432
    DB_NAME=mc_examgo          <- nama database yang baru dibuat
    DB_USER=postgres           <- username PostgreSQL
    DB_PASS=password_anda      <- password PostgreSQL
    DB_TIMEZONE=Asia/Jakarta   <- WIB | Asia/Makassar=WITA | Asia/Jayapura=WIT
    SERVER_PORT=8080

    JWT_SECRET=isi-dengan-karakter-acak-panjang-minimal-64-karakter
    JWT_STUDENT_SECRET=isi-dengan-karakter-berbeda-dari-jwt-secret-di-atas

Tips: Generate JWT Secret di https://generate-secret.vercel.app/64

### Langkah 3 — Migrasi Database (Sekali Saja)

Buka Command Prompt, arahkan ke folder ini:

    cd C:\path\ke\folder\MC-ExamGo-Win
    mc-exam-go-migrate.exe --seed

Tunggu hingga muncul:
AutoMigrate completed successfully!
Migration process finished.

### Langkah 4 — Jalankan Server

Double-click file: mc-exam-go-windows-amd64-v1.0.0.exe

Atau via Command Prompt:
mc-exam-go-windows-amd64-v1.0.0.exe

Jika muncul dialog Windows Firewall, klik [Allow Access].

### Langkah 5 — Akses Aplikasi

| URL                               | Keterangan                      |
| --------------------------------- | ------------------------------- |
| http://localhost:8080             | Halaman utama / login siswa     |
| http://localhost:8080/admin/login | Login admin                     |
| http://192.168.x.x:8080           | Akses dari komputer lain di LAN |

    Login Default Admin:
    Email    : admin@mc-exam.go
    Password : admin123

    !! SEGERA GANTI PASSWORD SETELAH LOGIN PERTAMA !!

---

---

## [B] INSTALASI DI LINUX / VPS

Gunakan binary dari folder bin/:

- Server : mc-exam-go-linux-amd64-v1.0.0 (Intel/AMD)
  mc-exam-go-linux-arm64-v1.0.0 (ARM/Oracle Cloud)
- Migrate: mc-exam-go-migrate-linux-amd64
  mc-exam-go-migrate-linux-arm64

### Langkah 1 — Install PostgreSQL di VPS

    sudo apt update
    sudo apt install -y postgresql postgresql-contrib
    sudo systemctl enable postgresql
    sudo systemctl start postgresql

Buat user dan database:

    sudo -u postgres psql

    -- Di dalam psql:
    CREATE USER mc_user WITH PASSWORD 'PasswordKuat!2026';
    CREATE DATABASE mc_examgo OWNER mc_user;
    GRANT ALL PRIVILEGES ON DATABASE mc_examgo TO mc_user;
    \q

### Langkah 2 — Upload File ke VPS

Dari komputer lokal (PowerShell/Terminal):

    scp mc-exam-go-linux-amd64-v1.0.0   user@IP_VPS:/opt/mc-examgo/
    scp mc-exam-go-migrate-linux-amd64  user@IP_VPS:/opt/mc-examgo/
    scp .env                             user@IP_VPS:/opt/mc-examgo/

### Langkah 3 — Setup Folder di VPS

    ssh user@IP_VPS

    sudo mkdir -p /opt/mc-examgo/uploads /opt/mc-examgo/logs
    sudo chmod +x /opt/mc-examgo/mc-exam-go-linux-amd64-v1.0.0
    sudo chmod +x /opt/mc-examgo/mc-exam-go-migrate-linux-amd64
    sudo chmod 600 /opt/mc-examgo/.env    # hanya owner yang bisa baca!

### Langkah 4 — Konfigurasi .env untuk VPS

    sudo nano /opt/mc-examgo/.env

Sesuaikan setting berikut:

    SERVER_PORT=8080
    DB_TIMEZONE=Asia/Jakarta

    DB_HOST=localhost
    DB_PORT=5432
    DB_NAME=mc_examgo
    DB_USER=mc_user
    DB_PASS=PasswordKuat!2026

    JWT_SECRET=isi-dengan-karakter-acak-panjang-minimal-64-karakter
    JWT_STUDENT_SECRET=isi-dengan-karakter-berbeda-dari-jwt-secret-di-atas

### Langkah 5 — Migrasi Database (Sekali Saja)

    cd /opt/mc-examgo
    ./mc-exam-go-migrate-linux-amd64 --seed

### Langkah 6 — Jalankan sebagai Service (Auto-Start)

Buat file service:

    sudo nano /etc/systemd/system/mc-examgo.service

Isi dengan:

    [Unit]
    Description=MC-ExamGO CBT Server
    After=network.target postgresql.service
    Wants=postgresql.service

    [Service]
    Type=simple
    User=www-data
    WorkingDirectory=/opt/mc-examgo
    ExecStart=/opt/mc-examgo/mc-exam-go-linux-amd64-v1.0.0
    Restart=on-failure
    RestartSec=5s
    StandardOutput=append:/opt/mc-examgo/logs/app.log
    StandardError=append:/opt/mc-examgo/logs/app.log

    [Install]
    WantedBy=multi-user.target

Aktifkan:

    sudo systemctl daemon-reload
    sudo systemctl enable mc-examgo
    sudo systemctl start mc-examgo
    sudo systemctl status mc-examgo

Lihat log realtime:

    sudo journalctl -u mc-examgo -f

### Langkah 7 — Setup Nginx Reverse Proxy (Opsional)

    sudo apt install -y nginx
    sudo nano /etc/nginx/sites-available/mc-examgo

Isi:

    server {
        listen 80;
        server_name cbts.sekolahanda.sch.id;

        client_max_body_size 50M;

        location / {
            proxy_pass http://127.0.0.1:8080;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_cache_bypass $http_upgrade;
            proxy_read_timeout 300s;
        }
    }

Aktifkan:

    sudo ln -s /etc/nginx/sites-available/mc-examgo /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl reload nginx

### HTTPS dengan Let's Encrypt

    sudo apt install -y certbot python3-certbot-nginx
    sudo certbot --nginx -d cbts.sekolahanda.sch.id

Setelah SSL aktif, update .env:
CORS_ORIGINS=https://cbts.sekolahanda.sch.id

Restart:
sudo systemctl restart mc-examgo

---

## [C] INSTALASI MENGGUNAKAN FASTPANEL (Linux VPS GUI)

Jika Anda mengelola VPS menggunakan **FastPanel** (Control Panel berbasis Web GUI), ikuti panduan langkah demi langkah berikut:

### Langkah 1 — Buat Database PostgreSQL di FastPanel

1. Login ke dashboard FastPanel (`https://IP-VPS:8888`).
2. Masuk ke menu **Databases** -> Klik **+ New database**.
3. Pilih Database Server: **PostgreSQL** _(Jika belum terpasang, instal PostgreSQL 1-klik dari menu Applications / Layanan FastPanel)_.
4. Masukkan nama database: `mc_examgo`.
5. Buat pengguna database baru: `mc_user` dengan password yang kuat.
6. Klik **Save**.

### Langkah 2 — Buat Situs (Domain / Subdomain) di FastPanel

1. Di dashboard FastPanel, klik tombol **+ Create site**.
2. Pilih opsi **Manual configuration** (atau PHP standar).
3. Masukkan domain / subdomain Anda (misal: `cbts.sekolahanda.sch.id`).
4. Tentukan user pengelola situs dan klik **Create**.
5. FastPanel akan membuat direktori root situs di: `/var/www/{user}/data/www/cbts.sekolahanda.sch.id`.

### Langkah 3 — Upload & Ekstrak File via File Manager FastPanel

1. Buka menu **Files (File Manager)** pada kartu situs yang baru dibuat.
2. Masuk ke direktori webroot tersebut dan hapus file `index.html` default jika ada.
3. Upload file paket `MC-ExamGo-amd64-v1.0.0.zip` (atau file binary `mc-exam-go-linux-amd64-v1.0.0`, `mc-exam-go-migrate-linux-amd64`, dan `.env`).
4. Ekstrak file zip ke direktori tersebut.
5. Buat folder baru bernama `uploads` dan `logs` (jika belum ada).
6. Edit file `.env` langsung dari File Manager FastPanel:

```env
SERVER_PORT=8080
DB_TIMEZONE=Asia/Jakarta

# Database PostgreSQL FastPanel
DB_HOST=127.0.0.1
DB_PORT=5432
DB_NAME=mc_examgo
DB_USER=mc_user
DB_PASS=PasswordKuatYangDibuatTadi

# Dual JWT Secrets (Wajib min. 64 karakter acak)
JWT_SECRET=isi-dengan-string-acak-panjang-min-64-karakter
JWT_STUDENT_SECRET=isi-dengan-string-acak-berbeda-untuk-siswa
```

### Langkah 4 — Beri Hak Eksekusi & Migrasi Database

Buka **Terminal SSH** di FastPanel (atau terminal SSH eksternal seperti PuTTY / Terminal), lalu jalankan:

```bash
# 1. Masuk ke direktori web situs Anda
cd /var/www/*/data/www/cbts.sekolahanda.sch.id

# 2. Beri izin eksekusi binary & proteksi .env
chmod +x mc-exam-go-linux-amd64-v1.0.0 mc-exam-go-migrate-linux-amd64
chmod 600 .env

# 3. Jalankan migrasi database
./mc-exam-go-migrate-linux-amd64 --seed
```

Tunggu hingga muncul konfirmasi `AutoMigrate completed successfully!`.

### Langkah 5 — Jalankan Server Daemon (Systemd Service)

Agar server Go terus aktif di latar belakang dan otomatis hidup saat VPS restart:

1. Buat file service Systemd:
   ```bash
   sudo nano /etc/systemd/system/mc-examgo.service
   ```
2. Salin konfigurasi berikut (sesuaikan path folder situs Anda):

   ```ini
   [Unit]
   Description=MC-ExamGO FastPanel Daemon Server
   After=network.target postgresql.service
   Wants=postgresql.service

   [Service]
   Type=simple
   User=root
   WorkingDirectory=/var/www/USER_ANDA/data/www/cbts.sekolahanda.sch.id
   ExecStart=/var/www/USER_ANDA/data/www/cbts.sekolahanda.sch.id/mc-exam-go-linux-amd64-v1.0.0
   Restart=always
   RestartSec=5s
   StandardOutput=append:/var/www/USER_ANDA/data/www/cbts.sekolahanda.sch.id/logs/app.log
   StandardError=append:/var/www/USER_ANDA/data/www/cbts.sekolahanda.sch.id/logs/app.log

   [Install]
   WantedBy=multi-user.target
   ```

3. Aktifkan dan jalankan service:
   ```bash
   sudo systemctl daemon-reload
   sudo systemctl enable --now mc-examgo
   sudo systemctl status mc-examgo
   ```

_(Alternatif: Anda juga dapat menggunakan PM2: `npm install -g pm2 && pm2 start ./mc-exam-go-linux-amd64-v1.0.0 --name "mc-examgo" && pm2 save && pm2 startup`)_

### Langkah 6 — Setup Nginx Reverse Proxy & SSL 1-Klik di FastPanel

1. Pada halaman dashboard FastPanel, buka situs Anda -> **Settings (Pengaturan)** -> **Manual Configuration (Konfigurasi Nginx)**.
2. Tambahkan / sesuaikan blok `location /` untuk mem-forward traffic ke port `8080`:
   ```nginx
   location / {
       proxy_pass http://127.0.0.1:8080;
       proxy_http_version 1.1;
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection 'upgrade';
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header X-Forwarded-Proto $scheme;
       proxy_read_timeout 300s;
   }
   ```
3. Klik **Save**.
4. Buka menu **SSL Certificates** pada situs di FastPanel -> Klik **+ New certificate** -> Pilih **Let's Encrypt** -> Centang opsi **Redirect HTTP to HTTPS** -> Klik **Save**.
5. Buka `https://cbts.sekolahanda.sch.id` di browser. Server MC-ExamGO siap digunakan! 🚀

---

---

## [D] TUNING PERFORMA VPS & NGINX (5.000 – 20.000+ SISWA SERENTAK)

Untuk memastikan server VPS mampu menampung lonjakan ribuan siswa login dan mengerjakan ujian serentak (*Avalanche Load*) tanpa mengalami *drop* koneksi:

### 1. Optimasi Kernel Linux (Sysctl & File Descriptors)
Jalankan perintah ini di terminal SSH root VPS:

```bash
# 1. Naikkan batas open file descriptors ke 65.535
ulimit -n 65535

# 2. Tambahkan tuning TCP Network di /etc/sysctl.conf
echo "net.core.somaxconn = 65535" >> /etc/sysctl.conf
echo "net.ipv4.tcp_max_syn_backlog = 65535" >> /etc/sysctl.conf
echo "net.ipv4.tcp_tw_reuse = 1" >> /etc/sysctl.conf
echo "net.ipv4.ip_local_port_range = 1024 65535" >> /etc/sysctl.conf

# Terapkan perubahan kernel
sysctl -p
```

### 2. Optimasi Nginx Global (`/etc/nginx/nginx.conf`)
Buka file konfigurasi global Nginx (`sudo nano /etc/nginx/nginx.conf`):

```nginx
user www-data;
worker_processes auto;
worker_rlimit_nofile 65535; # <── Tambahkan batas file descriptor worker

events {
    worker_connections 20480; # <── Izinkan hingga 20.480 koneksi per worker
    multi_accept on;
    use epoll;
}
```

### 3. Optimasi Upstream & Vhost Nginx (FastPanel / Standalone)
Pada file konfigurasi virtualhost Nginx situs CBT Anda, sesuaikan blok `upstream` dan `location /`:

```nginx
# Pipa koneksi persisten ke Go Backend
upstream mc_examgo_backend {
    server 127.0.0.1:8080;
    keepalive 512; # <── Wajib dinaikkan agar Nginx tidak terus membuka-tutup port lokal
}

server {
    server_name cbts.sekolahanda.sch.id;

    # ... konfigurasi SSL & Header ...

    location / {
        proxy_pass http://mc_examgo_backend;
        proxy_http_version 1.1;

        # Dukungan WebSocket / SSE & Telemetri Real-time
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;

        # Forward IP & Host
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header CF-Connecting-IP $http_cf_connecting_ip;

        # Buffer Tuning untuk Traffic Masif
        proxy_buffer_size 128k;
        proxy_buffers 4 256k;
        proxy_busy_buffers_size 256k;

        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}
```

Setelah itu reload Nginx:
```bash
nginx -t && systemctl reload nginx
```

---

## Konfigurasi AI Generator Soal

AI API Key TIDAK disimpan di .env — dikelola dari panel Admin:
Admin -> Pengaturan AI -> Tambah Provider -> Masukkan API Key

Provider yang didukung:

- OpenRouter : https://openrouter.ai/ (satu key untuk banyak model)
- Google AI : https://aistudio.google.com/ (Gemini)
- OpenAI : https://platform.openai.com/
- DeepSeek : https://platform.deepseek.com/

Rekomendasi Model (via OpenRouter):

| Model                        | Kualitas | Harga  | Cocok Untuk         |
| ---------------------------- | -------- | ------ | ------------------- |
| google/gemini-2.5-flash-lite | \*\*\*   | Murah  | Soal umum, cepat    |
| deepseek/deepseek-v3.2       | \*\*\*\* | Murah  | Matematika & logika |
| qwen/qwen3-32b               | \*\*\*\* | Sedang | Bahasa & narasi     |
| openai/gpt-4o-mini           | \*\*\*\* | Sedang | Serba bisa          |
| anthropic/claude-sonnet-4-5  | **\***   | Mahal  | Kualitas terbaik    |

Generate 100 soal ~ $0.01-$0.02 (model mid-range)
Budget $5 (~Rp82.000) cukup untuk puluhan ribu soal

CATATAN: Generate soal kadang error jika prompt terlalu rumit.
Solusi: generate ulang atau gunakan model yang lebih canggih.

---

---

## Troubleshooting

[ERROR] relation "users" does not exist
-> Jalankan: mc-exam-go-migrate.exe --seed

[ERROR] Failed to connect to database / failed SASL auth (FATAL: password authentication failed / SQLSTATE 28P01)
-> Pastikan PostgreSQL berjalan
-> Periksa DB_HOST, DB_USER, DB_PASS di .env (pastikan sama persis dengan kredensial PostgreSQL)
-> Jika password salah/belum diatur, reset di PostgreSQL:
sudo -u postgres psql
ALTER USER "mc-examgo" WITH PASSWORD 'password_baru_anda';
GRANT ALL PRIVILEGES ON DATABASE "mc-examgo" TO "mc-examgo";
\q

[ERROR] address already in use :8080
-> Port 8080 sudah dipakai. Ubah SERVER_PORT=9090 di .env

[ERROR] API 401 dan otomatis logout
-> Normal! Token JWT expired. User perlu login ulang.

[ERROR] Upload file gagal
-> Pastikan folder uploads/ ada di samping .exe
-> Linux: sudo chown -R www-data:www-data /opt/mc-examgo/uploads

[ERROR] AI Generator error / hasil tidak sesuai
-> Generate ulang atau gunakan model yang lebih pintar
-> Sederhanakan prompt tambahan

---

## Checklist Sebelum Go-Live

[ ] PostgreSQL terinstall dan berjalan
[ ] Database sudah dibuat
[ ] File .env sudah diisi lengkap
[ ] mc-exam-go-migrate.exe --seed sudah dijalankan
[ ] Server berhasil start tanpa error
[ ] Bisa akses http://localhost:8080
[ ] Login admin berhasil ( email : admin@mc-exam.go, pass: admin123 )
[ ] Password admin sudah diganti dari default
[ ] Lisensi sudah diaktivasi (jika PREMIUM)
[ ] AI API Key sudah ditambahkan (jika pakai fitur AI)

---

MC-ExamGO — Computer Based Test System
Versi: 1.0.0
