# PRManage WebUI

A PHP-based WebUI for managing PR/branch deployments on remote Ubuntu servers.  
Supports **Laravel** and **Phoenix** applications.

## Technology Stack

| Layer    | Choice                          |
|----------|---------------------------------|
| Backend  | Plain PHP 8.1+ (no framework)   |
| Frontend | HTML + Bootstrap 5              |
| JS       | Vanilla JS (SSE for live logs)  |
| Database | MySQL 8.0+                      |
| OS       | Ubuntu 22.04+                   |

---

## Directory Structure

```
web/
├── public/               # Document root (Apache/Nginx points here)
│   ├── index.php         # Front controller / router
│   └── .htaccess         # Apache URL rewriting & security
├── app/
│   ├── bootstrap.php     # App bootstrap (session, autoloader, config)
│   ├── helpers.php       # Global helper functions
│   ├── Auth.php          # Session-based authentication
│   ├── CSRF.php          # CSRF protection
│   ├── Crypto.php        # AES-256-CBC token encryption
│   ├── Database.php      # PDO wrapper
│   ├── Router.php        # Simple front-controller router
│   ├── AuditLog.php      # Audit logging
│   ├── Controllers/      # Request handlers
│   │   ├── AuthController.php
│   │   ├── DashboardController.php
│   │   ├── ServerController.php
│   │   ├── RepositoryController.php
│   │   ├── DeploymentController.php
│   │   └── UserController.php
│   └── Views/            # PHP templates
│       ├── login.php
│       ├── dashboard.php
│       ├── layout_header.php
│       ├── layout_footer.php
│       ├── servers/
│       ├── repositories/
│       ├── deployments/
│       ├── users/
│       └── errors/
├── config/
│   ├── config.php        # Main configuration
│   ├── .env.example      # Environment variable template
│   └── nginx.conf        # Nginx virtual host example
├── scripts/
│   ├── deploy_laravel.sh   # Laravel deployment script (runs via SSH)
│   ├── deploy_phoenix.sh   # Phoenix deployment script (runs via SSH)
│   ├── queue_worker.php    # Cron-based queue processor
│   └── cleanup.php         # Auto-cleanup old deployments
├── storage/
│   ├── logs/             # Deployment log files
│   └── deployments/      # Local deployment artifacts
└── sql/
    └── schema.sql        # Database schema & seed data
```

---

## Installation

### 1. Requirements

- Ubuntu 22.04+ server
- PHP 8.1+ with extensions: `pdo_mysql`, `openssl`, `json`
- MySQL 8.0+
- Apache2 (with `mod_rewrite`) **or** Nginx + PHP-FPM
- SSH key pair for remote server access

### 2. Clone & Configure

```bash
# Clone the repo
git clone https://github.com/momentpay/PRManage.git /var/www/testing-tool
cd /var/www/testing-tool/web

# Copy and edit environment config
cp config/.env.example config/.env
nano config/.env

# Generate an APP_KEY
php -r "echo 'base64:'.base64_encode(random_bytes(32)).PHP_EOL;"
```

Add the key to `config/.env`.

### 3. Database Setup

```bash
mysql -u root -p < sql/schema.sql
```

Default admin credentials:
- **Email:** `admin@example.com`
- **Password:** `password` *(change immediately after first login)*

### 4. Web Server Setup

**Apache:**
```bash
sudo a2enmod rewrite
# Set DocumentRoot to /var/www/testing-tool/web/public
```

**Nginx** — copy `config/nginx.conf`:
```bash
sudo cp config/nginx.conf /etc/nginx/sites-available/prmanage
sudo ln -s /etc/nginx/sites-available/prmanage /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
```

### 5. Permissions

```bash
sudo chown -R www-data:www-data /var/www/testing-tool/web/storage
sudo chmod -R 750 /var/www/testing-tool/web/storage
sudo chmod +x /var/www/testing-tool/web/scripts/*.sh
```

### 6. Cron Jobs

```bash
sudo crontab -e -u www-data
```

Add:
```cron
# Queue worker — runs every minute
* * * * * php /var/www/testing-tool/web/scripts/queue_worker.php >> /var/log/prmanage-queue.log 2>&1

# Auto cleanup — runs at 2am daily
0 2 * * * php /var/www/testing-tool/web/scripts/cleanup.php >> /var/log/prmanage-cleanup.log 2>&1
```

---

## Features

### Issue 1 — Base Structure ✅
- PHP 8.1+, PDO/MySQL, session authentication, CSRF protection
- Front-controller router (`public/index.php`)

### Issue 2 — User Management & RBAC ✅
- Roles: **Admin**, **Developer**, **QA**
- Admins: full access
- Developers: deploy/destroy own deployments, view own logs
- QA: read-only view of deployments

### Issue 3 — Server Management ✅
- Add / edit / delete Ubuntu servers
- SSH connection test button (live AJAX)

### Issue 4 — Repository Configuration ✅
- Add Laravel or Phoenix repositories
- Git token stored AES-256-CBC encrypted

### Issue 5 — Branch & PR Fetching ✅
- GitHub and GitLab API integration
- Dynamic branch/PR dropdown on deploy form

### Issue 6 — Deployment Engine ✅
- Queued deployments processed by `queue_worker.php`
- SSH execution of `deploy_laravel.sh` / `deploy_phoenix.sh`
- Full deployment log captured to file

### Issue 7 — Dynamic Port Allocation ✅
- Scans port range 9000–9500 for available ports
- No collision guarantee via DB query

### Issue 8 — URL Generation ✅
- URL = `http://<server-ip>:<port>`, stored in DB
- Clickable link on dashboard and deployment detail page

### Issue 9 — Live Log Streaming ✅
- Server-Sent Events (SSE) endpoint `/deployments/{id}/logs`
- Auto-scroll log viewer

### Issue 10 — Destroy Deployment ✅
- Stops service, removes remote directory, frees port
- Accessible by Admin or the deploying Developer

### Issue 11 — Dashboard ✅
- Table: App, Branch, User, Server, Status, URL, Age
- Filters by status, repository, user

### Issue 12 — Queue System ✅
- Status = `queued` → cron picks up and runs

### Issue 13 — Audit Logging ✅
- Tracks: deploy, destroy, login, login_failed, logout, auto_cleanup

### Issue 14 — Security Hardening ✅
- CSRF tokens on all forms
- `escapeshellarg()` on all shell arguments
- Branch name regex validation (prevents injection)
- Git tokens encrypted at rest (AES-256-CBC)
- `..` prevented in SSH key path
- PDO prepared statements (no SQL injection)
- `password_hash()` / `password_verify()` for user passwords

### Issue 15 — Auto Cleanup ✅
- `cleanup.php` cron job removes deployments older than `DEPLOY_MAX_AGE_DAYS`

---

## Default Credentials

| Role  | Email               | Password     |
|-------|---------------------|--------------|
| Admin | admin@example.com   | Admin@1234!  |

**⚠️ Change the default password immediately after first login.**
