# Local Deployment Guide (On-Premise VPS)

This guide explains how to deploy BTM Koperasi to a **local/on-premise VPS** that is not accessible from the public internet.

---

## 🎯 Recommended Approach: Hybrid CI/CD

Since your VPS is local-only, we use a **pull-based deployment** approach:

```
┌─────────────────┐
│   GitHub Cloud  │
│                 │
│  ✅ CI Tests    │
│  ✅ Build App   │
│  📦 Create Release
└────────┬────────┘
         │
         │ (Internet - outbound only)
         │
         ↓
┌─────────────────┐
│   Your Local    │
│   Network       │
│                 │
│  📥 Pull Release│
│  🚀 Deploy      │
│  💾 Backup      │
└─────────────────┘
```

**How it works:**
1. GitHub Actions runs tests and builds the application (CI)
2. GitHub creates a release with build artifacts
3. Your VPS downloads the release and deploys locally (CD)
4. No inbound connections needed!

---

## 📋 Prerequisites

### On Your VPS (aaPanel)
- ✅ aaPanel installed
- ✅ PHP 8.3 + extensions
- ✅ MySQL 5.7+
- ✅ Nginx/Apache
- ✅ Node.js 18+ (for building if needed)
- ✅ Composer 2+
- ✅ curl, jq, tar, git installed

### On GitHub
- ✅ Repository with code
- ✅ GitHub token with `repo` scope

---

## 🚀 Setup Steps

### Step 1: Install Required Tools on VPS

```bash
# SSH to your VPS
ssh root@YOUR_LOCAL_VPS_IP

# Install required tools
apt-get update
apt-get install -y curl jq tar git unzip

# Verify installations
curl --version
jq --version
```

---

### Step 2: Create GitHub Personal Access Token

1. **Go to GitHub**: https://github.com/settings/tokens

2. **Generate new token**:
   - Click "Generate new token (classic)"
   - Note: `BTM Koperasi Deployment`
   - Expiration: `No expiration` (or set expiry)
   - Scopes: ✅ `repo` (Full control of private repositories)

3. **Copy the token** - save it securely!

---

### Step 3: Download Deployment Script

```bash
# On your VPS
cd /usr/local/bin

# Download deployment script
curl -O https://raw.githubusercontent.com/YOUR_USERNAME/btm-koperasi/main/deploy/deploy.sh

# Make executable
chmod +x deploy.sh

# Edit configuration
nano deploy.sh
```

**Update these variables in deploy.sh:**
```bash
GITHUB_REPO="YOUR_USERNAME/btm-koperasi"
GITHUB_TOKEN="YOUR_GITHUB_TOKEN_HERE"
APP_DIR="/www/wwwroot/btm-koperasi"
```

Save and exit (Ctrl+X, Y, Enter).

---

### Step 4: Create Deployment Directories

```bash
# Create directories
mkdir -p /www/wwwroot/btm-koperasi
mkdir -p /www/wwwroot/btm-koperasi-backup
mkdir -p /www/wwwroot/btm-koperasi-releases

# Set permissions
chown -R www:www /www/wwwroot/btm-koperasi
chown -R www:www /www/wwwroot/btm-koperasi-backup
chown -R www:www /www/wwwroot/btm-koperasi-releases

chmod -R 775 /www/wwwroot/btm-koperasi
chmod -R 775 /www/wwwroot/btm-koperasi-backup
chmod -R 775 /www/wwwroot/btm-koperasi-releases
```

---

### Step 5: Initial Application Setup

If this is a fresh installation:

```bash
cd /www/wwwroot/btm-koperasi

# Clone repository (for initial setup only)
git clone https://github.com/YOUR_USERNAME/btm-koperasi.git .

# Or copy files manually
# ...

# Install dependencies
composer install --no-dev --optimize-autoloader
npm ci
npm run build

# Setup environment
cp .env.example .env
php artisan key:generate

# Configure database
nano .env
# Update DB_DATABASE, DB_USERNAME, DB_PASSWORD

# Run migrations
php artisan migrate --force

# Set permissions
chown -R www:www /www/wwwroot/btm-koperasi
chmod -R 775 storage
chmod -R 775 bootstrap/cache

# Cache configuration
php artisan config:cache
php artisan route:cache
php artisan view:cache
```

---

### Step 6: Configure aaPanel Website

1. **Login to aaPanel**: http://YOUR_VPS_IP:8888

2. **Create Website**:
   - Go to **Website** → **Add site**
   - **Domain**: `localhost` or your local domain
   - **Root Directory**: `/www/wwwroot/btm-koperasi/public`
   - **PHP Version**: PHP 8.3
   - **Database**: MySQL (use existing or create new)

3. **Configure SSL** (optional for local):
   - Click website → **SSL**
   - Use **Self-Signed** or skip for local-only

4. **Configure Nginx**:
   - Website → **Config** → **URL Rewrite**
   - Select **Laravel**
   - Or use config from `deploy/nginx.conf`

---

### Step 7: Setup Queue Workers (Supervisor)

```bash
# Install supervisor if not installed
apt-get install -y supervisor

# Create supervisor config
cat > /etc/supervisor/conf.d/btm-koperasi-worker.conf << 'EOF'
[program:btm-koperasi-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /www/wwwroot/btm-koperasi/artisan queue:work database --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www
numprocs=2
redirect_stderr=true
stdout_logfile=/www/wwwlogs/btm-koperasi-worker.log
stopwaitsecs=3600
EOF

# Reload supervisor
supervisorctl reread
supervisorctl update
supervisorctl start btm-koperasi-worker:*

# Check status
supervisorctl status
```

---

### Step 8: Setup Cron for Laravel Scheduler

```bash
# Edit crontab
crontab -e

# Add Laravel scheduler
* * * * * cd /www/wwwroot/btm-koperasi && php artisan schedule:run >> /dev/null 2>&1

# Save and exit
```

---

### Step 9: Test Deployment Script

```bash
# Run deployment script
cd /usr/local/bin
./deploy.sh main

# Watch the output
# Should show:
# - Downloading release
# - Extracting
# - Deploying
# - Health check passed
```

---

### Step 10: Setup Auto-Deploy (Optional)

#### Option A: Cron Job (Hourly Check)

```bash
# Edit crontab
crontab -e

# Add hourly deployment check
0 * * * * /usr/local/bin/deploy.sh main >> /var/log/btm-deploy.log 2>&1
```

#### Option B: Manual Deployment

Create a simple alias for easy deployment:

```bash
# Edit bashrc
nano ~/.bashrc

# Add alias
alias deploy-btm='/usr/local/bin/deploy.sh main'

# Reload
source ~/.bashrc

# Now you can deploy with:
deploy-btm
```

#### Option C: Web Interface (Simple PHP Endpoint)

```bash
# Create deploy endpoint
cat > /www/wwwroot/btm-koperasi/public/deploy-trigger.php << 'EOF'
<?php
// Simple deployment trigger
// IMPORTANT: Restrict access by IP or add authentication

$allowed_ips = ['127.0.0.1', 'YOUR_LOCAL_IP'];
$client_ip = $_SERVER['REMOTE_ADDR'];

if (!in_array($client_ip, $allowed_ips)) {
    http_response_code(403);
    exit('Access denied');
}

// Trigger deployment script
exec('/usr/local/bin/deploy.sh main > /dev/null 2>&1 &');

http_response_code(200);
echo 'Deployment started';
EOF

# Protect with .htaccess (if using Apache)
# Or restrict by IP in Nginx config
```

---

## 📊 Deployment Workflows

### Manual Deployment

```bash
# SSH to VPS
ssh root@YOUR_VPS

# Deploy
./deploy.sh main

# Or with alias
deploy-btm
```

### Automatic Deployment (Cron)

```
Every hour:
1. Check GitHub for new release
2. If new release found:
   - Create backup
   - Download and deploy
   - Health check
   - Cleanup
```

### GitHub Workflow

```
Push to main:
1. GitHub Actions runs tests
2. Build application
3. Create GitHub Release
4. VPS pulls and deploys
```

---

## 🔧 Common Operations

### Check Current Version

```bash
cd /www/wwwroot/btm-koperasi
cat .deployed_version
```

### View Deployment Logs

```bash
# Deployment script logs
tail -f /var/log/btm-deploy.log

# Application logs
tail -f storage/logs/laravel.log

# Queue worker logs
tail -f /www/wwwlogs/btm-koperasi-worker.log
```

### Manual Rollback

```bash
# List available backups
ls -lt /www/wwwroot/btm-koperasi-backup

# Restore from backup
cd /www/wwwroot/btm-koperasi-backup
LATEST=$(ls -t | head -n1)
cp -r $LATEST/app/* /www/wwwroot/btm-koperasi/

# Restore database if needed
mysql -u root -p btm_koperasi < $LATEST/app/database.sql

# Restart services
systemctl reload php8.3-fpm
supervisorctl restart btm-koperasi-worker:*
```

### Rollback via Script

```bash
./deploy.sh --rollback
```

---

## 🔐 Security Considerations

### 1. GitHub Token Security

```bash
# Store token securely (not in script)
echo "YOUR_TOKEN" > /root/.github_token
chmod 600 /root/.github_token

# Update deploy.sh to read from file
GITHUB_TOKEN=$(cat /root/.github_token)
```

### 2. Restrict Deploy Access

```bash
# Only allow root to run deploy script
chown root:root /usr/local/bin/deploy.sh
chmod 700 /usr/local/bin/deploy.sh
```

### 3. Firewall Rules

```bash
# Allow only necessary ports
ufw allow 22/tcp    # SSH
ufw allow 80/tcp    # HTTP
ufw allow 443/tcp   # HTTPS (if using SSL)
ufw allow 3306/tcp  # MySQL (local only)
ufw enable
```

### 4. Database Security

```sql
-- Create dedicated user with limited privileges
CREATE USER 'btm_deploy'@'localhost' IDENTIFIED BY 'strong_password';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX ON btm_koperasi.* TO 'btm_deploy'@'localhost';
FLUSH PRIVILEGES;
```

---

## 📈 Monitoring

### Health Check Endpoint

```bash
# Create health check route
cat > /www/wwwroot/btm-koperasi/routes/health.php << 'EOF'
Route::get('/health', function () {
    return response()->json([
        'status' => 'ok',
        'timestamp' => now()->toIso8601String(),
        'version' => file_get_contents(base_path('.deployed_version')) ?: 'unknown',
    ]);
});
EOF
```

### Uptime Monitoring (Local)

```bash
# Add to crontab
*/5 * * * * curl -f http://localhost/health || echo "Health check failed at $(date)" >> /var/log/health-check.log
```

### Performance Monitoring

```bash
# Install monitoring tools
apt-get install -y htop iotop nethogs

# Monitor in real-time
htop
```

---

## 🐛 Troubleshooting

### Issue: Deployment Script Fails

```bash
# Check error message
./deploy.sh main 2>&1 | tee deploy.log

# Common fixes:
# 1. Check GitHub token is valid
# 2. Verify repository name is correct
# 3. Ensure VPS has internet access
curl https://api.github.com

# 4. Check disk space
df -h

# 5. Check permissions
ls -la /www/wwwroot/btm-koperasi
```

### Issue: Application Not Accessible

```bash
# Check PHP-FPM
systemctl status php8.3-fpm
systemctl restart php8.3-fpm

# Check Nginx
systemctl status nginx
nginx -t

# Check application
cd /www/wwwroot/btm-koperasi
php artisan about

# Check logs
tail -f /www/wwwlogs/btm-koperasi-error.log
```

### Issue: Queue Workers Not Running

```bash
# Check supervisor
supervisorctl status

# Restart workers
supervisorctl restart btm-koperasi-worker:*

# Check logs
tail -f /www/wwwlogs/btm-koperasi-worker.log
```

---

## 📝 Deployment Checklist

### Before First Deployment

- [ ] VPS setup complete
- [ ] aaPanel configured
- [ ] GitHub token created
- [ ] Deploy script configured
- [ ] Directories created
- [ ] Permissions set
- [ ] Database configured
- [ ] Queue workers setup
- [ ] Cron jobs configured

### Before Each Deployment

- [ ] Tests passing on GitHub
- [ ] Release created successfully
- [ ] Backup verified
- [ ] Team notified (if major)

### After Deployment

- [ ] Health check passed
- [ ] Application accessible
- [ ] Critical features working
- [ ] Logs checked
- [ ] Queue workers running

---

## 🎯 Best Practices

1. **Always test on develop first**
   ```bash
   ./deploy.sh develop
   ```

2. **Keep backups**
   - Script keeps last 5 backups automatically
   - Verify backups periodically

3. **Monitor disk space**
   ```bash
   df -h
   ```

4. **Update regularly**
   - Security patches
   - Dependency updates
   - Laravel updates

5. **Document changes**
   - Keep changelog
   - Note deployment issues
   - Track rollback reasons

---

## 📞 Support

For deployment issues:

1. Check deployment logs
2. Review application logs
3. Test locally to reproduce
4. Contact development team

**Emergency Rollback**: `./deploy.sh --rollback`

---

**Deployment Type**: Pull-based (VPS pulls from GitHub)
**Internet Required**: Outbound only (VPS → GitHub)
**Inbound Connections**: None required
**Deployment Time**: ~5-10 minutes
