# Production deployment — Ubuntu server

Target: **Ubuntu 24.04 LTS**, one server running Nginx, PHP-FPM 8.5, MySQL 8.4, Redis, a queue worker
(Supervisor) and the scheduler (cron). Times are Asia/Dubai.

| Size | Users | Server |
|---|---|---|
| Small | up to ~30 | 2 vCPU, 4 GB RAM, 80 GB SSD |
| Medium | up to ~150 | 4 vCPU, 8 GB RAM, 160 GB SSD |

Disk use grows with contract documents and backups (allow ~3× document storage for backups). Put
off-site backups on S3-compatible storage (§10).

---

## 1. Server basics

```bash
sudo apt update && sudo apt -y upgrade
sudo timedatectl set-timezone Asia/Dubai
sudo adduser --disabled-password --gecos "" almasa          # the app/deploy user
sudo usermod -aG www-data almasa

# Firewall: SSH + web only
sudo ufw allow OpenSSH && sudo ufw allow 'Nginx Full' && sudo ufw --force enable

# Automatic security updates
sudo apt -y install unattended-upgrades && sudo dpkg-reconfigure -plow unattended-upgrades
```

Harden SSH: use key login only (`PasswordAuthentication no` in `/etc/ssh/sshd_config`) and keep
`PermitRootLogin no`.

## 2. Packages

```bash
sudo add-apt-repository -y ppa:ondrej/php && sudo apt update
sudo apt -y install nginx mysql-server redis-server supervisor unzip git \
  php8.5-fpm php8.5-cli php8.5-bcmath php8.5-curl php8.5-gd php8.5-intl php8.5-mbstring \
  php8.5-mysql php8.5-redis php8.5-xml php8.5-zip php8.5-readline php8.5-igbinary \
  tesseract-ocr tesseract-ocr-ara tesseract-ocr-eng poppler-utils mysql-client

# Composer
curl -sS https://getcomposer.org/installer | php && sudo mv composer.phar /usr/local/bin/composer
# Node.js 22 (front-end build only)
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash - && sudo apt -y install nodejs
```

## 3. MySQL and Redis

```bash
sudo mysql_secure_installation
sudo mysql -e "CREATE DATABASE almasa_cms CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
  CREATE USER 'almasa'@'localhost' IDENTIFIED BY 'CHANGE-ME-long-random';
  GRANT ALL PRIVILEGES ON almasa_cms.* TO 'almasa'@'localhost'; FLUSH PRIVILEGES;"
```

*Optional, stronger audit protection:* after the first `migrate`, use a second DB user for the app with
only `SELECT, INSERT` on `audit_logs` (run migrations with the full user). Entries then can't be edited
even with direct database access.

Redis: in `/etc/redis/redis.conf` keep `bind 127.0.0.1 ::1`, set `requirepass <long-random>`, then
`sudo systemctl restart redis-server`.

## 4. PHP tuning

`/etc/php/8.5/fpm/conf.d/99-almasa.ini`:

```ini
memory_limit = 512M
upload_max_filesize = 105M
post_max_size = 110M
max_execution_time = 120
expose_php = Off
opcache.enable = 1
opcache.memory_consumption = 256
opcache.interned_strings_buffer = 32
opcache.max_accelerated_files = 30000
opcache.validate_timestamps = 0      ; code changes only via deploy.sh (it reloads PHP-FPM)
realpath_cache_size = 4096K
realpath_cache_ttl = 600
```

Copy the same file to `/etc/php/8.5/cli/conf.d/` for the queue worker, but keep
`opcache.validate_timestamps = 1` there. Then run `sudo systemctl restart php8.5-fpm`.

## 5. Application

### 5a. Get the files onto the server

The application goes in **`/var/www/almasa`** on the server. Only the `public/` folder inside it is
served to the web (Nginx `root`, §6). Everything else, including `.env`, stays private.

Never upload these from your PC; the server creates or installs them:
- `.env` (your local one has local passwords)
- `vendor/` and `node_modules/`
- the contents of `storage/`, such as local documents, logs and backups

The release zip below already leaves them out.

**Option A — release zip (simplest).** On your PC, create a clean package from the committed code:

```bash
git archive --format=zip -o ../almasa-cms-release.zip HEAD
```

Upload it with **WinSCP** (free, <https://winscp.net>) or FileZilla:
1. New session → protocol **SFTP**, host = server IP, user = `almasa` (SSH key or password from your
   hosting provider). Port 22.
2. Drag `almasa-cms-release.zip` into `/home/almasa/`.

Then on the server (connect with PuTTY, Windows Terminal `ssh almasa@SERVER-IP`, or the provider's web
console):

```bash
sudo mkdir -p /var/www/almasa && sudo chown almasa:www-data /var/www/almasa
sudo -iu almasa
cd /var/www/almasa && unzip -q ~/almasa-cms-release.zip && rm ~/almasa-cms-release.zip
chmod +x deploy.sh
cp .env.example .env
```

**Option B — private Git repository (best for updates).** Push the code to a **private** GitHub/GitLab
repository, add the server's SSH key as a read-only *deploy key*, then:

```bash
sudo mkdir -p /var/www/almasa && sudo chown almasa:www-data /var/www/almasa
sudo -iu almasa
git clone git@github.com:<your-org>/almasa-cms.git /var/www/almasa
cd /var/www/almasa && cp .env.example .env
```

With Git, every later update is just `./deploy.sh` (§9). With the zip, upload the new zip, unzip it over
the folder (your `.env` and `storage/` are kept, because the zip doesn't contain them), then run
`./deploy.sh`.

### 5b. Configure

Edit `.env`. The production values that matter:

```env
APP_NAME="Almasa CMS"
APP_ENV=production
APP_DEBUG=false
APP_URL=https://contracts.almasa.ae
APP_TIMEZONE=Asia/Dubai
APP_LOCALE=ar

DB_HOST=127.0.0.1
DB_DATABASE=almasa_cms
DB_USERNAME=almasa
DB_PASSWORD=...

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=...
QUEUE_CONNECTION=redis
CACHE_STORE=redis
SESSION_DRIVER=database
SESSION_SECURE_COOKIE=true
SESSION_ENCRYPT=true

LOG_LEVEL=info
PASSWORD_CHECK_UNCOMPROMISED=true

SEED_ADMIN_EMAIL=you@almasa.ae
SEED_ADMIN_PASSWORD=...              # first login only — change it after signing in

BACKUP_ARCHIVE_PASSWORD=...          # long random; store a copy OFF the server
```

Mail, WhatsApp, Telegram and AI: see [CREDENTIALS_SETUP.md](CREDENTIALS_SETUP.md).

First install:

```bash
composer install --no-dev --optimize-autoloader
php artisan key:generate                 # ONCE. Back up APP_KEY: it decrypts settings and sessions
npm ci && npm run build
php artisan migrate --seed --force       # roles, master data, default rules, Super Admin
php artisan storage:link
php artisan optimize && php artisan filament:optimize
sudo chown -R almasa:www-data storage bootstrap/cache
sudo chmod -R ug+rwX storage bootstrap/cache
```

Then remove `SEED_ADMIN_PASSWORD` from `.env`.

## 6. Nginx + HTTPS

`/etc/nginx/sites-available/almasa`:

```nginx
server {
    listen 80;
    server_name contracts.almasa.ae;
    root /var/www/almasa/public;
    index index.php;
    client_max_body_size 110M;
    server_tokens off;

    # /storage is public (logo only); never execute or sniff content there
    location /storage/ {
        add_header X-Content-Type-Options nosniff always;
        add_header Content-Security-Policy "default-src 'none'; img-src 'self'" always;
        try_files $uri =404;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.5-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_read_timeout 120;
    }

    location ~ /\.(?!well-known) { deny all; }
}
```

```bash
sudo ln -s /etc/nginx/sites-available/almasa /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx
sudo apt -y install certbot python3-certbot-nginx
sudo certbot --nginx -d contracts.almasa.ae --redirect     # auto-renews
```

The app adds its own security headers (CSP, frame, referrer…) and HSTS on HTTPS.

## 7. Queue worker (Supervisor)

`/etc/supervisor/conf.d/almasa-worker.conf`:

```ini
[program:almasa-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/almasa/artisan queue:work redis --queue=notifications,extraction,default --timeout=900 --sleep=3 --max-time=3600 --tries=3
user=almasa
numprocs=2
autostart=true
autorestart=true
stopwaitsecs=960
redirect_stderr=true
stdout_logfile=/var/www/almasa/storage/logs/worker.log
stdout_logfile_maxbytes=20MB
```

```bash
sudo supervisorctl reread && sudo supervisorctl update && sudo supervisorctl status
```

`numprocs=2` lets a long OCR/AI extraction run without blocking reminders. Raise it for heavy import days.

## 8. Scheduler (cron)

```bash
sudo crontab -u almasa -e
# add:
* * * * * cd /var/www/almasa && php artisan schedule:run >> /dev/null 2>&1
```

This drives the 06:00 expiry check, task reminders, report pruning and the nightly backups
(01:30 clean, 02:00 backup, 08:00 monitor), plus the health heartbeats.

## 9. Updating (each release)

```bash
sudo -iu almasa
cd /var/www/almasa && ./deploy.sh
```

`deploy.sh` turns on maintenance mode, pulls the code, installs dependencies, builds the theme, backs up
the database, migrates, rebuilds caches, restarts workers, reloads PHP-FPM and turns the site back on.
Give the deploy user passwordless sudo for `systemctl reload php8.5-fpm` only:

```bash
echo 'almasa ALL=(root) NOPASSWD: /usr/bin/systemctl reload php8.5-fpm' | sudo tee /etc/sudoers.d/almasa
```

## 10. Off-site backups (recommended)

Add an S3-compatible bucket (AWS S3, Wasabi, Backblaze B2, DigitalOcean Spaces) to `.env`:

```env
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
AWS_DEFAULT_REGION=me-central-1
AWS_BUCKET=almasa-cms-backups
BACKUP_DISKS=backups,s3
```

Then run `composer require league/flysystem-aws-s3-v3 "^3.0"` and `./deploy.sh`. Use a bucket with
versioning or object lock, and an access key limited to that bucket. Restore steps:
[BACKUP_RESTORE.md](BACKUP_RESTORE.md).

## 11. Go-live checklist

- [ ] `APP_ENV=production`, `APP_DEBUG=false`, HTTPS working, HTTP redirects to HTTPS
- [ ] **System → System health** all green (scheduler and queue within minutes of starting)
- [ ] First backup created (**System → Backups → Back up now**) and a test restore done once
- [ ] `APP_KEY` and `BACKUP_ARCHIVE_PASSWORD` stored off the server
- [ ] Super Admin password changed; seed password removed from `.env`
- [ ] Mail test received; WhatsApp/Telegram tested or switched off
- [ ] Company details and logo entered (Settings Center)
- [ ] Users created with the right roles and departments
- [ ] `ufw status` shows only SSH and 80/443; MySQL and Redis listen on localhost only
