# Updating an Existing PBX

How to pull the latest code changes from Bitbucket to a client machine.

---

## Standard Update (one command)

```bash
sudo bash /var/www/html/scripts/pbx-update.sh
```

### What it does

1. `git pull origin main` — pulls latest code from Bitbucket
2. `composer install` — installs any new PHP packages
3. `php artisan migrate` — applies any new database schema changes
4. Rebuilds config, route, and view caches
5. Fixes file ownership (`www-data`)
6. Reloads Asterisk dialplan
7. Reconciles AstDB (clears stale CF/DND/queue state)

### Dry run (preview without changing anything)

```bash
sudo bash /var/www/html/scripts/pbx-update.sh --check
```

---

## What gets updated

| Updated | Not updated |
|---|---|
| All PHP application code | `.env` (your local config) |
| Blade views / templates | `/etc/asterisk/*` (system configs) |
| Database migrations (schema only) | Database content (extensions, CDR, etc.) |
| Artisan commands | Firewall rules |
| Scripts in `scripts/` | SSL certificates |

---

## After updating

Check the health page to confirm everything is still green:

**Settings → System Health**

If anything shows red after an update, the most common fixes are:

```bash
# Rebuild caches manually
sudo -u www-data php /var/www/html/artisan config:clear
sudo -u www-data php /var/www/html/artisan cache:clear
sudo -u www-data php /var/www/html/artisan view:clear

# Re-sync dialplan
sudo -u www-data php /var/www/html/artisan pbx:sync-blf-hints
sudo -u www-data php /var/www/html/artisan pbx:sync-did-normalizer

# Fix permissions
chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache
```

---

## Checking the current version

```bash
git -C /var/www/html log --oneline -5
```

This shows the last 5 commits — the top one is what's currently running.

---

## If git isn't set up yet on this machine

This happens if the machine was cloned but never connected to Bitbucket.
See [new-client-setup.md](new-client-setup.md) Step 1 to connect the repo first.

Quick version:
```bash
# 1. Generate SSH key and add to Bitbucket access keys
ssh-keygen -t ed25519 -C "vconnect-client-$(hostname)" -f /root/.ssh/bitbucket_pbx -N ""
cat /root/.ssh/bitbucket_pbx.pub
# → Add this to https://bitbucket.org/openvdev/vconnectpbx/admin/access-keys/

# 2. Configure SSH
cat > /root/.ssh/config << 'EOF'
Host bitbucket.org
    HostName bitbucket.org
    User git
    IdentityFile /root/.ssh/bitbucket_pbx
    IdentitiesOnly yes
EOF
chmod 600 /root/.ssh/config

# 3. Connect repo
git config --global --add safe.directory /var/www/html
git -C /var/www/html init
git -C /var/www/html remote add origin git@bitbucket.org:openvdev/vconnectpbx.git
git -C /var/www/html fetch origin
git -C /var/www/html reset --hard origin/main

# 4. Now updates work normally
sudo bash /var/www/html/scripts/pbx-update.sh
```
