# CD Deployment Guide - aaPanel VPS

This guide walks you through setting up continuous deployment to your aaPanel VPS.

---

## 📋 Prerequisites

### Server Requirements
- **OS**: Ubuntu 20.04+ / CentOS 7+ / Debian 10+
- **PHP**: 8.3+ with extensions (mbstring, xml, curl, mysql, pdo, sqlite3, intl, zip, gd, bcmath)
- **Database**: MySQL 5.7+ / MariaDB 10.3+
- **Node.js**: 18+ (for build process)
- **Composer**: 2.0+
- **Web Server**: Nginx or Apache (via aaPanel)
- **SSH Access**: Root or sudo user

### aaPanel Required Plugins
Install these from aaPanel App Store:
- ✅ Nginx (or Apache)
- ✅ PHP 8.3
- ✅ MySQL
- ✅ phpMyAdmin
- ✅ Supervisor (for queue workers)
- ✅ Redis (optional, for caching)

---

## 🚀 Server Setup

### Step 1: Run Setup Script

Upload and run the setup script on your VPS:

```bash
# Upload script to server
scp deploy/setup-aapanel.sh root@your-server-ip:/tmp/

# SSH into server
ssh root@your-server-ip

# Run setup script
chmod +x /tmp/setup-aapanel.sh
bash /tmp/setup-aapanel.sh
```

The script will:
- Create application directories
- Install PHP extensions
- Install Composer & Node.js
- Create database and user
- Configure Supervisor for queues
- Setup cron jobs
- Create initial .env file

### Step 2: Configure Website in aaPanel

1. **Login to aaPanel** (http://your-ip:8888)

2. **Create Website**:
   - Go to **Website** → **Add site**
   - **Domain**: your-domain.com
   - **Root Directory**: `/www/wwwroot/btm-koperasi/public`
   - **PHP Version**: PHP 8.3
   - **Database**: MySQL (use credentials from setup script)

3. **Configure SSL**:
   - Click on your website → **SSL**
   - Select **Let's Encrypt**
   - Enter email and domains
   - Click **Apply**

4. **Configure Nginx** (if using Nginx):
   - Go to your website → **Config** → **URL Rewrite**
   - Select **Laravel** from dropdown
   - Or use this configuration:

```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;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
}

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

5. **Set Directory Permissions**:
   ```bash
   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
   ```

---

## 🔐 GitHub Secrets Configuration

Add these secrets to your GitHub repository:

### Required Secrets

Go to: **Repository Settings** → **Secrets and variables** → **Actions** → **New repository secret**

| Secret Name | Value | Example |
|-------------|-------|---------|
| `SSH_PRIVATE_KEY` | SSH private key for deployment | `-----BEGIN OPENSSH PRIVATE KEY-----...` |
| `SSH_HOST` | Your VPS IP address or hostname | `123.45.67.89` |
| `SSH_USERNAME` | SSH username | `root` or `deploy` |
| `DB_PASSWORD` | Database password | `your_db_password` |
| `APP_URL` | Your production domain | `btm-koperasi.com` |

### Optional Secrets

| Secret Name | Value | Purpose |
|-------------|-------|---------|
| `PRODUCTION_ENV` | Complete .env content | Override default .env |
| `DEPLOY_PATH` | Custom deployment path | `/var/www/btm-koperasi` |
| `BACKUP_PATH` | Custom backup location | `/backups/btm-koperasi` |
| `SLACK_WEBHOOK_URL` | Slack webhook URL | Deployment notifications |

### How to Generate SSH Key

```bash
# On your local machine
ssh-keygen -t ed25519 -C "github-deploy" -f ~/.ssh/github_deploy_btm

# Copy private key
cat ~/.ssh/github_deploy_btm | pbcopy  # macOS
cat ~/.ssh/github_deploy_btm | clip   # Windows

# Copy public key to server
ssh-copy-id -i ~/.ssh/github_deploy_btm.pub root@your-server-ip

# Test connection
ssh -i ~/.ssh/github_deploy_btm root@your-server-ip
```

**Important**: Paste the **entire** private key (including `-----BEGIN...` and `-----END...`) into the `SSH_PRIVATE_KEY` secret.

---

## 🎯 Deployment Workflows

### Automatic Deployment

The CD workflow triggers automatically when:
- Code is pushed to `main` branch
- All tests pass
- Build succeeds

### Manual Deployment

1. Go to **Actions** tab
2. Select **Deploy to Production** workflow
3. Click **Run workflow**
4. Choose options:
   - **Environment**: production or staging
   - **Skip tests**: Deploy without running tests (use with caution)
   - **Run migrations**: Execute database migrations

---

## 📊 Deployment Process

Here's what happens during deployment:

```
┌─────────────────────────────────────────────────────────────┐
│ 1. Pre-Deployment Checks                                    │
│    ✓ Get version info                                       │
│    ✓ Validate inputs                                        │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│ 2. Run Tests (can be skipped)                              │
│    ✓ PHP linting (Pint)                                     │
│    ✓ Pest tests                                             │
│    ✓ Build assets                                           │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│ 3. Build Application                                        │
│    ✓ Install dependencies                                   │
│    ✓ Build frontend (SSR)                                   │
│    ✓ Optimize autoloader                                    │
│    ✓ Create build artifact                                  │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│ 4. Deploy to VPS                                            │
│    ✓ Create backup (app + database)                         │
│    ✓ Upload new build                                       │
│    ✓ Set permissions                                        │
│    ✓ Install dependencies                                   │
│    ✓ Run migrations                                         │
│    ✓ Clear & cache config                                   │
│    ✓ Restart PHP-FPM                                        │
│    ✓ Restart queue workers                                  │
│    ✓ Health check                                           │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│ 5. Post-Deployment                                          │
│    ✓ Clean old releases                                     │
│    ✓ Send notifications                                     │
│    ✓ Update deployment status                               │
└─────────────────────────────────────────────────────────────┘
```

**Duration**: ~5-10 minutes

---

## 🔄 Rollback

Automatic rollback occurs if:
- Health check fails
- Deployment script errors

### Manual Rollback

```bash
# SSH to server
ssh root@your-server-ip

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

# Restore from specific backup
cd /www/wwwroot/btm-koperasi-backup
cp -r 20260326_120000/current /www/wwwroot/btm-koperasi

# Restore database
mysql -u root btm_koperasi < /www/wwwroot/btm-koperasi-backup/20260326_120000/database_backup.sql

# Restart services
systemctl reload php8.3-fpm
systemctl restart supervisor
```

---

## 🔍 Monitoring & Troubleshooting

### View Deployment Logs

1. **GitHub Actions Logs**:
   - Go to **Actions** tab
   - Select workflow run
   - View detailed logs for each job

2. **Server Logs**:
   ```bash
   # Application logs
   tail -f /www/wwwlogs/btm-koperasi-error.log
   tail -f /www/wwwlogs/btm-koperasi-access.log
   
   # Laravel logs
   tail -f /www/wwwroot/btm-koperasi/storage/logs/laravel.log
   
   # Queue worker logs
   tail -f /www/wwwlogs/btm-koperasi-worker.log
   
   # Supervisor status
   supervisorctl status
   ```

### Common Issues

#### 1. SSH Connection Failed
```
Error: Permission denied (publickey)
```
**Solution**: 
- Verify SSH key is correctly added to GitHub secrets
- Ensure public key is in `~/.ssh/authorized_keys` on server
- Test connection: `ssh -i ~/.ssh/key root@server-ip`

#### 2. Database Migration Failed
```
SQLSTATE[HY000] [2002] Connection refused
```
**Solution**:
- Check MySQL is running: `systemctl status mysqld`
- Verify DB credentials in .env
- Ensure DB host is `127.0.0.1` not `localhost`

#### 3. Permission Denied
```
Permission denied: /www/wwwroot/btm-koperasi/storage
```
**Solution**:
```bash
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
```

#### 4. 502 Bad Gateway
```
Error 502: Bad Gateway
```
**Solution**:
```bash
# Check PHP-FPM
systemctl status php8.3-fpm

# Restart PHP-FPM
systemctl restart php8.3-fpm

# Check if site is accessible
curl http://localhost
```

#### 5. Queue Workers Not Running
```
Jobs not being processed
```
**Solution**:
```bash
# Check supervisor
supervisorctl status

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

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

---

## 📈 Optimization Tips

### 1. Enable OPcache
In aaPanel → PHP 8.3 → Config → OPcache:
```ini
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.revalidate_freq=60
```

### 2. Configure Redis Cache
```env
CACHE_STORE=redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASSWORD=null
```

### 3. Optimize Database
Add indexes to frequently queried columns:
```sql
ALTER TABLE members ADD INDEX idx_email (email);
ALTER TABLE transactions ADD INDEX idx_date (transaction_date);
```

### 4. Enable Gzip Compression
In aaPanel → Website → Config → Gzip:
```
Enable Gzip: ON
Level: 6
```

---

## 🛡️ Security Best Practices

### 1. Firewall Configuration
```bash
# Allow only necessary ports
ufw allow 22/tcp    # SSH
ufw allow 80/tcp    # HTTP
ufw allow 443/tcp   # HTTPS
ufw enable
```

### 2. Disable Directory Browsing
In Nginx config:
```nginx
autoindex off;
```

### 3. Secure .env
```bash
chmod 644 /www/wwwroot/btm-koperasi/.env
chown www:www /www/wwwroot/btm-koperasi/.env
```

### 4. Regular Updates
```bash
# Weekly security updates
apt-get update && apt-get upgrade -y

# Update Composer dependencies
composer update --no-dev --optimize-autoloader
```

---

## 📊 Environment Comparison

| Setting | Development | Staging | Production |
|---------|-------------|---------|------------|
| `APP_DEBUG` | true | true | false |
| `APP_ENV` | local | staging | production |
| `LOG_LEVEL` | debug | info | error |
| `CACHE_STORE` | array | database | redis |
| `QUEUE_CONNECTION` | sync | database | database |
| Migrations | Manual | Auto | Auto |
| Tests | Required | Required | Optional |

---

## 🎛️ Advanced Configuration

### Multi-Server Deployment

For multiple servers, create separate environments:

```yaml
# .github/environments/production.yml
servers:
  - host: server1.com
    username: deploy
    path: /var/www/app
  - host: server2.com
    username: deploy
    path: /var/www/app
```

### Blue-Green Deployment

Modify the CD workflow to:
1. Deploy to inactive environment
2. Run smoke tests
3. Switch load balancer
4. Keep old environment as backup

### Database Migration Strategy

For zero-downtime migrations:
1. Deploy code compatible with old and new schema
2. Run migrations in background
3. Deploy final code requiring new schema

---

## 📞 Support

For deployment issues:
1. Check this guide first
2. Review GitHub Actions logs
3. Check server logs
4. Contact the development team

**Emergency Rollback**: Always have a rollback plan before deploying to production.

---

## 📝 Checklist

### Before First Deployment
- [ ] Server setup completed
- [ ] aaPanel configured
- [ ] Website created in aaPanel
- [ ] SSL certificate installed
- [ ] GitHub secrets configured
- [ ] SSH key tested
- [ ] Database created
- [ ] .env file configured
- [ ] Test deployment to staging

### Before Each Deployment
- [ ] Tests passing locally
- [ ] Changelog reviewed
- [ ] Database backup verified
- [ ] Rollback plan ready
- [ ] Team notified (if major changes)

### After Deployment
- [ ] Health check passed
- [ ] Application accessible
- [ ] Critical features working
- [ ] Logs checked for errors
- [ ] Performance acceptable
- [ ] Team notified of completion

---

**Deployment workflow created**: `.github/workflows/cd-deploy.yml`

**Next**: Run the setup script on your VPS and configure GitHub secrets!
