# Local/On-Premise Deployment Strategies

Since your VPS is only accessible locally (not from the public internet), GitHub Actions **cannot directly deploy** to it. Here are the solutions:

---

## ❌ Why Current CD Won't Work

```
GitHub Actions (Cloud)
        ↓
    [Internet]
        ↓
    [Firewall/NAT]
        ↓
    [Local Network] → Your VPS
        ✗ No direct access!
```

GitHub Actions runs on GitHub's servers and cannot:
- SSH into your local network
- Access private IP addresses (192.168.x.x, 10.x.x.x)
- Bypass your firewall/NAT

---

## ✅ Solution 1: Self-Hosted Runner (RECOMMENDED)

Run GitHub Actions **locally** on a machine in your network.

### How It Works

```
Your Local Network:
┌──────────────────────────────────────┐
│  GitHub Runner (your PC/server)      │
│    ↓                                 │
│    Deploys to VPS                    │
│    (same network, no firewall)       │
└──────────────────────────────────────┘
        ↕ (via GitHub)
GitHub Repository
```

### Setup Steps

1. **Install GitHub Runner** on a local PC/server:
   ```bash
   # Download runner
   mkdir actions-runner && cd actions-runner
   curl -O -L https://github.com/actions/runner/releases/download/v2.321.0/actions-runner-linux-x64-2.321.0.tar.gz
   tar xzf ./actions-runner-linux-x64-2.321.0.tar.gz
   ```

2. **Register with GitHub**:
   - Go to: Repo Settings → Actions → Runners
   - Click "New self-hosted runner"
   - Follow instructions (download token, run config)

3. **Update CD workflow**:
   ```yaml
   runs-on: self-hosted  # Instead of ubuntu-latest
   ```

### Pros
- ✅ Full GitHub Actions integration
- ✅ Works with existing CD workflow
- ✅ No cloud deployment needed
- ✅ Fast (local network)

### Cons
- ⚠️ Need a machine always on
- ⚠️ Runner must be secured
- ⚠️ Manual runner updates

### Best For
- Teams with always-on local server
- Production environment on local network

---

## ✅ Solution 2: Pull-Based Deployment (RECOMMENDED)

VPS **pulls** updates from GitHub instead of GitHub pushing to VPS.

### How It Works

```
GitHub Repository
    ↓ (webhook or poll)
Deploy Script on VPS
    ↓
Pull code from GitHub
    ↓
Deploy locally
```

### Setup Steps

1. **Create deploy script on VPS** (`/usr/local/bin/deploy-btm.sh`):
   ```bash
   #!/bin/bash
   set -e
   
   APP_DIR="/www/wwwroot/btm-koperasi"
   BACKUP_DIR="/www/wwwroot/btm-koperasi-backup"
   
   cd $APP_DIR
   
   # Create backup
   TIMESTAMP=$(date +%Y%m%d_%H%M%S)
   cp -r $APP_DIR $BACKUP_DIR/$TIMESTAMP
   
   # Pull latest code
   git fetch origin main
   git reset --hard origin/main
   
   # Install dependencies
   composer install --no-dev --optimize-autoloader
   
   # Build assets
   npm ci
   npm run build
   
   # Run migrations
   php artisan migrate --force
   
   # Clear cache
   php artisan config:cache
   php artisan route:cache
   
   # Restart services
   systemctl reload php8.3-fpm
   supervisorctl restart btm-koperasi-worker:*
   
   echo "✅ Deployment complete!"
   ```

2. **Make executable**:
   ```bash
   chmod +x /usr/local/bin/deploy-btm.sh
   ```

3. **Trigger deployment** (choose one):

   **Option A: Manual SSH**
   ```bash
   ssh root@YOUR_VPS
   /usr/local/bin/deploy-btm.sh
   ```

   **Option B: Webhook Listener** (see Solution 3)

   **Option C: Cron Job** (auto-deploy every hour)
   ```bash
   crontab -e
   # Add: 0 * * * * /usr/local/bin/deploy-btm.sh >> /var/log/deploy.log 2>&1
   ```

### Pros
- ✅ No inbound connections needed
- ✅ Simple to setup
- ✅ VPS controls when to update
- ✅ Works behind any firewall

### Cons
- ⚠️ VPS needs outbound internet access
- ⚠️ Slightly more complex workflow

### Best For
- Local/behind-firewall deployments
- Environments with strict security

---

## ✅ Solution 3: Webhook Auto-Deploy

GitHub notifies VPS when code is pushed, VPS deploys itself.

### How It Works

```
Push to GitHub
    ↓
GitHub Webhook
    ↓
Webhook Listener on VPS (port 80/443 forwarded)
    ↓
Trigger deploy script
```

### Setup Steps

1. **Create webhook listener** on VPS:
   ```bash
   # Install Node.js
   npm install -g github-webhook-cli
   
   # Or create simple PHP listener
   cat > /www/wwwroot/btm-koperasi/public/deploy.php << 'EOF'
   <?php
   // Simple webhook listener
   $secret = 'YOUR_WEBHOOK_SECRET';
   
   $headers = getallheaders();
   $signature = $headers['X-Hub-Signature-256'] ?? '';
   $payload = file_get_contents('php://input');
   
   // Verify signature (simplified)
   if ($signature !== 'sha256=' . hash_hmac('sha256', $payload, $secret)) {
       http_response_code(403);
       exit('Invalid signature');
   }
   
   // Run deploy script
   exec('/usr/local/bin/deploy-btm.sh > /dev/null 2>&1 &');
   
   http_response_code(200);
   echo 'Deployment started';
   EOF
   ```

2. **Configure GitHub Webhook**:
   - Repo Settings → Webhooks → Add webhook
   - Payload URL: `http://YOUR_LOCAL_IP/deploy.php`
   - Content type: `application/json`
   - Secret: `YOUR_WEBHOOK_SECRET`
   - Events: Push to `main`

3. **Port Forwarding** (if needed):
   - Forward port 80/8080 from router to VPS
   - Or use ngrok for tunneling

### Pros
- ✅ Automatic deployment
- ✅ No manual intervention
- ✅ Real-time updates

### Cons
- ⚠️ Requires port forwarding or tunneling
- ⚠️ Security considerations
- ⚠️ More complex setup

### Best For
- Automated local deployments
- Teams wanting GitHub-like experience

---

## ✅ Solution 4: Hybrid Approach (RECOMMENDED)

Use GitHub Actions for **CI** (testing), local deployment for **CD**.

### How It Works

```
Push to GitHub
    ↓
GitHub Actions (CI)
    ✅ Run tests
    ✅ Build artifacts
    ↓
Download artifact on VPS
    ↓
VPS deploys locally
```

### Setup Steps

1. **CI workflow** (unchanged) - runs tests and creates build artifact

2. **On VPS, create pull-deploy script**:
   ```bash
   #!/bin/bash
   # deploy-from-github.sh
   
   APP_DIR="/www/wwwroot/btm-koperasi"
   GITHUB_TOKEN="YOUR_GITHUB_TOKEN"
   REPO="username/btm-koperasi"
   
   cd $APP_DIR
   
   # Download latest successful build
   curl -L \
     -H "Authorization: token $GITHUB_TOKEN" \
     -H "Accept: application/vnd.github.v3+json" \
     "https://api.github.com/repos/$REPO/actions/artifacts" \
     | jq '.artifacts[0].archive_download_url' \
     | xargs curl -L -O - \
       -H "Authorization: token $GITHUB_TOKEN"
   
   # Extract and deploy
   unzip artifact.zip
   # ... (deploy steps)
   ```

3. **Trigger manually or via cron**

### Pros
- ✅ Best of both worlds
- ✅ Tests run in cloud
- ✅ Deployment stays local
- ✅ No self-hosted runner needed

### Cons
- ⚠️ More complex setup
- ⚠️ Need GitHub token

### Best For
- Most local production setups
- Teams wanting CI benefits without cloud CD

---

## ✅ Solution 5: Manual Deploy with Build Artifacts

Simplest approach - build in CI, deploy manually.

### Workflow

1. **CI creates release** on GitHub
2. **Download release** on VPS
3. **Manual deploy script**

### Setup

1. **Update CI to create releases**:
   ```yaml
   - name: Create Release
     uses: softprops/action-gh-release@v1
     with:
       files: build/
       tag_name: v${{ github.run_number }}
   ```

2. **On VPS**:
   ```bash
   # Download latest release
   wget https://github.com/YOU/btm-koperasi/releases/latest/download/build.zip
   
   # Deploy
   unzip build.zip -d /www/wwwroot/btm-koperasi
   cd /www/wwwroot/btm-koperasi
   composer install --no-dev
   php artisan migrate --force
   # ... etc
   ```

### Pros
- ✅ Simplest setup
- ✅ Full control
- ✅ No automation risks

### Cons
- ⚠️ Manual process
- ⚠️ Human error possible

### Best For
- Small teams
- Infrequent deployments
- High-security environments

---

## 🎯 Recommendation Matrix

| Your Situation | Recommended Solution |
|----------------|---------------------|
| Have always-on local server | **Solution 1**: Self-hosted runner |
| Want automation, no extra hardware | **Solution 2**: Pull-based deployment |
| Want real-time auto-deploy | **Solution 3**: Webhook auto-deploy |
| Want CI testing + local CD | **Solution 4**: Hybrid approach |
| Simple, manual control | **Solution 5**: Manual with releases |

---

## 🚀 My Recommendation for You

Based on your setup (local VPS, BTM Koperasi), I recommend:

### **Solution 2: Pull-Based Deployment** + **Solution 4: Hybrid CI**

**Why:**
1. ✅ No need for always-on runner machine
2. ✅ CI tests still run in cloud (quality assurance)
3. ✅ VPS pulls when ready (flexible)
4. ✅ Simple and reliable
5. ✅ Works with any firewall setup

**Setup:**
1. Keep existing CI workflow (tests, build)
2. Create simple deploy script on VPS
3. Trigger manually or via cron
4. Optional: Add webhook for auto-trigger

---

## 📝 Next Steps

Tell me which solution you prefer, and I'll:
1. Create the specific deployment scripts
2. Update the GitHub workflows
3. Provide step-by-step setup guide
4. Create rollback procedures

**Which solution interests you most?**
