# 🚀 Pull-Based Deployment - Complete Setup Guide

**Recommended for: Local/On-Premise VPS (not publicly accessible)**

---

## 📋 What You'll Get

✅ **Automated deployment** from GitHub Releases
✅ **Zero-downtime** deployment
✅ **Automatic backup** before deploy
✅ **Auto-rollback** on failure
✅ **Health checks** after deployment
✅ **No inbound connections** required

---

## ⏱️ Setup Time: 15-20 minutes

---

## Part 1: GitHub Setup (5 minutes)

### Step 1.1: Create GitHub Personal Access Token

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

2. **Click**: "Generate new token (classic)"

3. **Fill in**:
   - **Note**: `BTM Koperasi Deployment`
   - **Expiration**: `No expiration` (or 90 days)
   - **Scopes**: ✅ Check `repo` (Full control of private repositories)

4. **Click**: "Generate token"

5. **Copy the token** - Save it securely! (You won't see it again)

---

### Step 1.2: Verify CI Workflow Exists

Ensure `.github/workflows/ci-build.yml` exists in your repository.

This workflow:
- Runs tests on push/PR
- Builds the application
- Creates GitHub Releases automatically

**Test it**:
```bash
# Push to main branch
git add .
git commit -m "Test CI workflow"
git push origin main
```

Check Actions tab - should see "CI - Build and Release" workflow running.

---

## Part 2: VPS Setup (10 minutes)

### Step 2.1: SSH to Your VPS

```bash
ssh root@YOUR_VPS_IP
```

---

### Step 2.2: Install Required Tools

```bash
# Update package list
apt-get update

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

# Verify installations
curl --version
jq --version
git --version

echo "✅ Tools installed successfully"
```

---

### Step 2.3: 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
mkdir -p /tmp/btm-deploy

# 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
chown -R www:www /tmp/btm-deploy

chmod -R 775 /www/wwwroot/btm-koperasi
chmod -R 775 /www/wwwroot/btm-koperasi-backup
chmod -R 775 /www/wwwroot/btm-koperasi-releases
chmod -R 775 /tmp/btm-deploy

echo "✅ Directories created"
```

---

### Step 2.4: Store GitHub Token Securely

```bash
# Create token file
nano /root/.github_token

# Paste your GitHub token (from Step 1.1)
# Then save (Ctrl+X, Y, Enter)

# Set secure permissions
chmod 600 /root/.github_token

# Verify
cat /root/.github_token
# Should show your token

echo "✅ Token stored securely"
```

---

### Step 2.5: Download Deployment Script

```bash
# Download script
curl -L https://raw.githubusercontent.com/YOUR_USERNAME/btm-koperasi/main/deploy/deploy.sh \
  -o /usr/local/bin/deploy.sh

# Make executable
chmod +x /usr/local/bin/deploy.sh

# Verify
ls -lh /usr/local/bin/deploy.sh

echo "✅ Script downloaded"
```

---

### Step 2.6: Configure Deployment Script

```bash
# Edit script
nano /usr/local/bin/deploy.sh
```

**Find and update these lines** (around line 20-30):

```bash
# Change this:
GITHUB_REPO="YOUR_GITHUB_USERNAME/btm-koperasi"

# To your actual repo:
GITHUB_REPO="yourusername/btm-koperasi"
```

**The script will automatically read the token from `/root/.github_token`**

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

---

### Step 2.7: Verify Script Configuration

```bash
# Test script (show help)
/usr/local/bin/deploy.sh --help

# List available releases (tests GitHub connection)
/usr/local/bin/deploy.sh --list
```

You should see available releases from GitHub.

**If you see "Bad credentials"**: Check your GitHub token
**If you see "No release found"**: Make sure CI workflow created a release

---

## Part 3: Initial Application Setup (If Fresh Install)

### Step 3.1: First Deployment

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

This will:
1. Check prerequisites
2. Download latest release from GitHub
3. Extract to application directory
4. Set permissions
5. Run initial setup

---

### Step 3.2: Configure Environment

```bash
# Edit .env file
nano /www/wwwroot/btm-koperasi/.env
```

**Update these values**:

```env
APP_NAME="BTM Koperasi"
APP_ENV=production
APP_DEBUG=false
APP_URL=http://YOUR_VPS_IP

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=btm_koperasi
DB_USERNAME=btm_user
DB_PASSWORD=YOUR_DB_PASSWORD

# Configure mail if needed
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your-email@gmail.com
MAIL_PASSWORD=your-app-password
```

Save and exit.

---

### Step 3.3: Generate Application Key

```bash
cd /www/wwwroot/btm-koperasi
php artisan key:generate

echo "✅ Application key generated"
```

---

### Step 3.4: Run Migrations

```bash
php artisan migrate --force

echo "✅ Migrations completed"
```

---

### Step 3.5: Setup Queue Workers

```bash
# 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

echo "✅ Queue workers configured"
```

---

### Step 3.6: Setup Laravel Scheduler

```bash
# Edit crontab
crontab -e

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

# Save and exit

echo "✅ Scheduler configured"
```

---

### Step 3.7: Cache Configuration

```bash
php artisan config:cache
php artisan route:cache
php artisan view:cache

echo "✅ Configuration cached"
```

---

## Part 4: aaPanel Website Configuration

### Step 4.1: Login to aaPanel

```
http://YOUR_VPS_IP:8888
```

---

### Step 4.2: Create Website

1. **Go to**: Website → Add site

2. **Fill in**:
   - **Domain**: `YOUR_VPS_IP` or local domain
   - **Root Directory**: `/www/wwwroot/btm-koperasi/public`
   - **PHP Version**: PHP 8.3
   - **Database**: MySQL (use existing or create new)

3. **Click**: Submit

---

### Step 4.3: Configure Nginx

1. **Click** on your website → **Config**

2. **Go to**: URL Rewrite

3. **Select**: Laravel from dropdown

4. **Or paste this**:

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

location ~ \.php$ {
    fastcgi_pass unix:/tmp/php-cgi-83.sock;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

location ~ /\.ht {
    deny all;
}
```

5. **Click**: Save

---

### Step 4.4: Configure SSL (Optional for Local)

1. **Click** on website → **SSL**

2. **Select**: Let's Encrypt

3. **Enter email** and domain

4. **Click**: Apply

**Or use Self-Signed** for local-only access.

---

### Step 4.5: Test Website

```bash
# Test from VPS
curl http://localhost

# Should return HTML

# Test from browser
http://YOUR_VPS_IP
```

---

## Part 5: Test Deployment

### Step 5.1: Make a Change

On your local computer:

```bash
# Make a small change
echo "<?php // Test" >> app/Http/Controllers/TestController.php

# Commit and push
git add .
git commit -m "Test deployment"
git push origin main
```

---

### Step 5.2: Wait for CI

1. **Go to**: GitHub repository → Actions
2. **Check**: "CI - Build and Release" workflow
3. **Wait**: For workflow to complete (~5-10 minutes)
4. **Verify**: Release created in Releases tab

---

### Step 5.3: Deploy on VPS

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

# Deploy
/usr/local/bin/deploy.sh main
```

**Watch the output** - should show:
- ✅ Backup created
- ✅ Release downloaded
- ✅ Files extracted
- ✅ Deployment complete
- ✅ Health check passed

---

### Step 5.4: Verify Deployment

```bash
# Check version
cat /www/wwwroot/btm-koperasi/.deployed_version

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

# Test in browser
http://YOUR_VPS_IP
```

---

## 🎯 Deployment Workflow

### Automated Deployment

```bash
# Deploy from main
./deploy.sh main

# Deploy from develop
./deploy.sh develop
```

### Manual Deployment with Options

```bash
# Deploy without backup
./deploy.sh --no-backup main

# Deploy without health check
./deploy.sh --no-check main

# Deploy and skip cleanup
./deploy.sh --no-cleanup main
```

### Rollback

```bash
# Rollback to previous version
./deploy.sh --rollback
```

### List Releases

```bash
# See available releases
./deploy.sh --list
```

### Cleanup

```bash
# Clean old releases
./deploy.sh --cleanup
```

### Help

```bash
# Show all options
./deploy.sh --help
```

---

## 📊 What Happens During Deployment

```
1. Pre-deployment checks
   ✓ Check prerequisites
   ✓ Verify GitHub token
   ✓ Check internet connectivity

2. Backup (2-3 minutes)
   ✓ Backup application files
   ✓ Backup database
   ✓ Clean old backups

3. Download release (1-2 minutes)
   ✓ Fetch latest release from GitHub
   ✓ Download artifact
   ✓ Verify checksum

4. Extract and deploy (2-3 minutes)
   ✓ Extract release
   ✓ Copy files to app directory
   ✓ Set permissions
   ✓ Run post-deploy script

5. Health check (1 minute)
   ✓ Check app accessibility
   ✓ Verify database connection
   ✓ Check storage permissions

6. Cleanup (30 seconds)
   ✓ Clean old releases
   ✓ Clean downloads
```

**Total time**: ~5-10 minutes

---

## 🔧 Common Operations

### Check Current Version

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

### View Deployment History

```bash
ls -lt /www/wwwroot/btm-koperasi-releases
```

### View Backups

```bash
ls -lt /www/wwwroot/btm-koperasi-backup
```

### View Logs

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

# Application logs
tail -f /www/wwwroot/btm-koperasi/storage/logs/laravel.log

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

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

### Manual Rollback

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

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

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

---

## 🐛 Troubleshooting

### Issue: "GitHub token not configured"

**Solution**:
```bash
# Check token file exists
ls -l /root/.github_token

# If not, create it
echo "YOUR_TOKEN" > /root/.github_token
chmod 600 /root/.github_token
```

---

### Issue: "No release found"

**Solution**:
1. Check CI workflow ran successfully
2. Check releases exist: https://github.com/YOUR_USERNAME/btm-koperasi/releases
3. Verify branch name matches

---

### Issue: "Checksum verification failed"

**Solution**:
```bash
# Clean downloads
rm -rf /tmp/btm-deploy/*

# Try again
./deploy.sh main
```

---

### Issue: "Health check failed"

**Solution**:
```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: "Permission denied"

**Solution**:
```bash
# Fix permissions
chown -R www:www /www/wwwroot/btm-koperasi
chmod -R 775 /www/wwwroot/btm-koperasi/storage
chmod -R 775 /www/wwwroot/btm-koperasi/bootstrap/cache
```

---

## ✅ Best Practices

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

2. **Backup before major deployments**
   ```bash
   # Manual backup
   TIMESTAMP=$(date +%Y%m%d_%H%M%S)
   cp -r /www/wwwroot/btm-koperasi /www/wwwroot/btm-koperasi-backup/$TIMESTAMP
   ```

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

4. **Keep deploy script updated**
   ```bash
   curl -L https://raw.githubusercontent.com/YOUR_USERNAME/btm-koperasi/main/deploy/deploy.sh \
     -o /usr/local/bin/deploy.sh
   chmod +x /usr/local/bin/deploy.sh
   ```

5. **Document deployments**
   ```bash
   # Add to deploy.sh
   echo "$(date): Deployed version $DEPLOYED_VERSION" >> /var/log/btm-deployments.log
   ```

---

## 📈 Monitoring Setup

### Simple Uptime Monitor

```bash
# Add to crontab
crontab -e

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

### Disk Space Alert

```bash
# Add to crontab
0 * * * * df -h | awk 'NR==2 {if ($5+0 > 90) print "Disk usage: " $5}' | \
  mail -s "Disk Alert" your-email@example.com
```

---

## 🎉 You're Done!

Your pull-based deployment system is ready!

### Quick Reference

```bash
# Deploy
./deploy.sh main

# Rollback
./deploy.sh --rollback

# List releases
./deploy.sh --list

# Help
./deploy.sh --help
```

### Next Steps

1. ✅ Test deployment workflow
2. ✅ Setup monitoring
3. ✅ Configure backups verification
4. ✅ Train team on deployment process

---

**Need Help?**
- Check logs: `tail -f /var/log/btm-deploy.log`
- Review guide: [LOCAL_DEPLOYMENT_GUIDE.md](LOCAL_DEPLOYMENT_GUIDE.md)
- Quick reference: [LOCAL_DEPLOYMENT_QUICKREF.md](LOCAL_DEPLOYMENT_QUICKREF.md)

**Happy Deploying!** 🚀
