# Forgejo Actions CI/CD Setup Guide

**Successfully implemented comprehensive CI/CD pipeline for HVAC Community Events WordPress plugin**

## 🚀 Implementation Summary

### ✅ Completed Tasks

1. **Repository Migration**: Full GitHub → Forgejo migration with complete history preservation
2. **CI/CD Pipeline**: Comprehensive Forgejo Actions workflows implemented
3. **Security Integration**: Multi-layer security scanning and compliance monitoring
4. **GitOps Workflows**: Automated deployment with rollback capabilities

## 📁 Pipeline Structure

### Primary Workflows

```
.forgejo/workflows/
├── ci.yml                    # Main CI/CD pipeline
├── gitops.yml               # GitOps deployment automation  
└── security-monitoring.yml  # Security scanning & compliance
```

## 🔧 Pipeline Features

### 1. Main CI/CD Pipeline (`ci.yml`)

**Triggers:**
- Push to `main` or `develop` branches
- Pull requests to `main`
- Daily security scans (2 AM UTC)

**Jobs:**
- **Security Scan**: PHPCS Security Audit, Semgrep, credential detection
- **Code Quality**: WordPress Coding Standards, PHPStan, PHPMD
- **Unit Tests**: PHPUnit with WordPress test framework
- **Integration Tests**: Playwright E2E tests with WordPress setup
- **Deploy Staging**: Automated staging deployment (develop branch)
- **Deploy Production**: Manual approval required (main branch with `[deploy-production]`)

### 2. GitOps Deployment (`gitops.yml`)

**Capabilities:**
- Manual and automated deployments
- Environment-specific configurations (staging/production)
- Pre-deployment validation and health checks
- Automatic backup creation before deployment
- One-click rollback to previous versions
- Post-deployment verification

**Supported Actions:**
- `deploy`: Deploy to staging or production
- `rollback`: Rollback to previous backup
- `health-check`: Comprehensive environment validation

### 3. Security Monitoring (`security-monitoring.yml`)

**Scans:**
- **Daily**: Dependency vulnerabilities, secrets detection
- **Weekly**: Comprehensive OWASP Top 10 compliance audit
- **On Push**: WordPress security patterns, code analysis

**Tools Integrated:**
- NPM Audit & Composer Security Checker
- detect-secrets & TruffleHog for credential scanning
- Semgrep for static code analysis
- WordPress-specific security patterns
- OWASP compliance validation

## 🔒 Security Configuration Required

### Repository Secrets Setup

Navigate to your Forgejo repository → Settings → Secrets and add:

#### Staging Environment
```bash
STAGING_SSH_KEY          # SSH private key for staging server
STAGING_HOST             # upskill-staging.measurequick.com
STAGING_SSH_USER         # root
STAGING_WP_PATH          # /var/www/html
STAGING_URL              # https://upskill-staging.measurequick.com
```

#### Production Environment  
```bash
PRODUCTION_SSH_KEY       # SSH private key for production server
PRODUCTION_HOST          # 146.190.76.204 or upskillhvac.com
PRODUCTION_SSH_USER      # benr
PRODUCTION_WP_PATH       # /var/www/html
PRODUCTION_URL           # https://upskillhvac.com
```

### SSH Key Generation (If Needed)

```bash
# Generate deployment key
ssh-keygen -t ed25519 -C "forgejo-actions-deployment" -f deployment_key

# Add public key to server authorized_keys
cat deployment_key.pub >> ~/.ssh/authorized_keys

# Add private key to Forgejo repository secrets
cat deployment_key  # Copy to STAGING_SSH_KEY or PRODUCTION_SSH_KEY
```

## 🚀 Deployment Workflows

### Automatic Deployment

**Staging**: Automatic on push to `develop` branch
```bash
git push origin develop  # Triggers staging deployment
```

**Production**: Manual approval required
```bash
git commit -m "feat: new feature [deploy-production]"
git push origin main  # Requires manual approval in Actions
```

### Manual Deployment via API

```bash
# Deploy to staging
curl -X POST \
  -H "Authorization: token YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"event_type":"deploy-staging","client_payload":{"environment":"staging","action":"deploy"}}' \
  https://git.tealmaker.com/api/v1/repos/ben/upskill-event-manager/dispatches

# Deploy to production  
curl -X POST \
  -H "Authorization: token YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"event_type":"deploy-production","client_payload":{"environment":"production","action":"deploy"}}' \
  https://git.tealmaker.com/api/v1/repos/ben/upskill-event-manager/dispatches

# Rollback staging
curl -X POST \
  -H "Authorization: token YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"event_type":"deploy-staging","client_payload":{"environment":"staging","action":"rollback"}}' \
  https://git.tealmaker.com/api/v1/repos/ben/upskill-event-manager/dispatches
```

### Manual Deployment via Forgejo UI

1. Navigate to **Actions** tab in repository
2. Select **GitOps Deployment Automation** workflow
3. Click **Run workflow**
4. Choose:
   - **Environment**: staging or production
   - **Action**: deploy, rollback, or health-check
   - **Version**: specific tag/commit (optional)

## 📊 Monitoring & Compliance

### Security Dashboard

**Daily Reports**: Automated vulnerability scanning
**Weekly Audits**: Comprehensive OWASP Top 10 compliance
**Real-time Alerts**: Critical security issues trigger immediate notifications

### Available Reports

Access via **Actions** → **Artifacts** after pipeline runs:

- `security-report`: Semgrep and vulnerability analysis
- `coverage-report`: PHPUnit test coverage
- `integration-test-results`: E2E test results and screenshots
- `dependency-scan-reports`: NPM and Composer vulnerability reports
- `secrets-scan-reports`: Credential exposure analysis
- `final-security-report`: Comprehensive security summary

## 🔧 Local Development Integration

### Running Tests Locally

```bash
# Security scan
composer global require automattic/phpcs-security-audit
phpcs --standard=Security --extensions=php .

# Unit tests  
phpunit --coverage-html=coverage/

# Integration tests
HEADLESS=true node test-master-trainer-e2e.js
```

### Pre-commit Validation

```bash
# Use existing validation script
./scripts/pre-deployment-check.sh

# Or run individual checks
phpcs --standard=WordPress --extensions=php .
npm audit --audit-level=moderate
```

## 🚨 Emergency Procedures

### Quick Rollback

If production deployment fails:

1. **Via Forgejo UI**:
   - Actions → GitOps Deployment → Run workflow
   - Environment: production, Action: rollback

2. **Via Command Line**:
   ```bash
   ./scripts/deploy.sh production rollback
   ```

### Health Check

Verify environment status:
```bash
# Via pipeline
curl -X POST -H "Authorization: token YOUR_TOKEN" \
  -d '{"event_type":"deploy-production","client_payload":{"environment":"production","action":"health-check"}}' \
  https://git.tealmaker.com/api/v1/repos/ben/upskill-event-manager/dispatches

# Via script
./scripts/deploy.sh production health-check
```

## 🎯 Next Steps

### Phase 2: Test Framework Migration (Pending)

1. **Migrate 80+ Test Files**: Convert to new Page Object Model architecture
2. **Setup Test Environments**: Docker Compose for hermetic testing
3. **Implement Test Data Management**: Automated seeding and cleanup
4. **Performance Optimization**: Parallel execution and storage state caching

### Phase 3: Advanced GitOps

1. **Multi-environment Support**: Dev, staging, production pipeline
2. **Blue-Green Deployments**: Zero-downtime deployment strategy
3. **Canary Releases**: Gradual rollout with monitoring
4. **Infrastructure as Code**: Terraform integration

## 📚 Documentation References

- **Pipeline Configuration**: `.forgejo/workflows/` directory
- **Security Framework**: `docs/SECURITY-INCIDENT-REPORT.md`
- **Test Modernization Plan**: `docs/COMPREHENSIVE-TESTING-MODERNIZATION-PLAN.md`
- **WordPress Best Practices**: `docs/CLAUDE-CODE-DEVELOPMENT-BEST-PRACTICES.md`

---

**Status**: ✅ **IMPLEMENTATION COMPLETE**  
**Date**: 2025-08-27  
**Pipeline Status**: 🟢 Active and monitoring  
**Next Phase**: Test framework migration (80+ files)