# Installing the billing system (Ubuntu 22.04 / 24.04 or Debian 12, Apache)

About 30 minutes on a fresh server. Every command runs as root (`sudo -i`) unless stated. Replace `billing.example.com` with your domain and `/var/www/billing` with your path if you change it.

```
Customers ──443──▶ Apache ─▶ PHP-FPM ─▶ MariaDB         one site: https://billing.example.com
MikroTik ──UDP 51820──▶ WireGuard hub (wg0, 10.99.0.1) ──▶ Apache tunnel listener 10.99.0.1:8081 (router config scripts)
                                          └──▶ the app talks to each router's API through the tunnel
Safaricom ──▶ https://billing.example.com/api/…   (STK and Paybill callbacks)
```

For the system.eazyradius.co.ke server, follow the ready-to-paste [INSTALL_EAZYRADIUS.md](INSTALL_EAZYRADIUS.md).

Upgrading a server that still runs the old multi-tenant version? Go to [Moving from the multi-tenant version](#moving-from-the-multi-tenant-version).

## 0. Before you start
| You need | Notes |
|---|---|
| A server with a public IPv4 | 1 vCPU / 1 GB RAM is enough to start |
| A domain with DNS you control | one record: `billing.example.com` → the server. If you use Cloudflare, set it to **DNS only** (grey cloud): WireGuard on UDP 51820 cannot go through the proxy. No wildcard record or wildcard certificate is needed |
| Open ports | TCP 80, TCP 443, **UDP 51820** |
| Routers | MikroTik **RouterOS 7.x** for WireGuard provisioning |
| Optional | M-Pesa Daraja credentials (STK push, Paybill), an SMS gateway account (Africa's Talking or any HTTP API), GenieACS for ONUs |

## 1. Packages
```bash
apt-get update
apt-get install -y apache2 mariadb-server git curl unzip \
  php-fpm php-mysql php-curl php-mbstring php-xml
php -v                                         # 8.1 or newer
php -m | grep -E "pdo_mysql|sodium|curl|mbstring"   # all four must be listed
a2enmod rewrite ssl headers proxy_fcgi setenvif
a2enconf "$(basename /etc/apache2/conf-available/php*-fpm.conf .conf)"   # e.g. php8.3-fpm
systemctl restart apache2
```

## 2. Get the code
```bash
git clone https://github.com/dkaranj/radiuscloud.git /var/www/billing
cd /var/www/billing
```
Code stays owned by root and readable by the web user; the application never writes into its own folder.

## 3. Database
```bash
DBPASS=$(openssl rand -base64 18 | tr -d '/+=')   # note it down: you need it in step 4
mysql -e "CREATE DATABASE billing CHARACTER SET utf8mb4;
          CREATE USER 'billing'@'localhost' IDENTIFIED BY '$DBPASS';
          GRANT ALL ON billing.* TO 'billing'@'localhost';"
mysql billing < database/schema.sql      # complete schema, already includes every migration
```

## 4. Configure
```bash
cp config/config.sample.php config/config.php
php -r 'echo base64_encode(random_bytes(32)), "\n";'      # → paste as app_key
nano config/config.php
```
| Key | Value |
|---|---|
| `db` → `dsn`, `user`, `pass` | `mysql:host=127.0.0.1;dbname=billing;charset=utf8mb4`, `billing`, the password from step 3 |
| `app_key` | the generated key. **Back it up and never change it**: it encrypts M-Pesa credentials, SMS keys, router passwords and WireGuard keys. A new key makes them unreadable |
| `public_url` | `https://billing.example.com`. M-Pesa callbacks and portal links are built from this |
| `timezone` | e.g. `Africa/Nairobi` |

The `wireguard` block is filled in at step 8.
```bash
chown root:www-data config/config.php && chmod 640 config/config.php   # the file holds the DB password and app key
php bin/migrate.php --baseline        # records the bundled migrations as already applied (schema.sql contains them)
```

## 5. TLS certificate
M-Pesa callbacks and the hotspot portal need HTTPS. Get a normal certificate for your one domain:
```bash
apt-get install -y certbot
systemctl stop apache2                 # certbot's standalone mode needs port 80 for a moment
certbot certonly --standalone -d billing.example.com
systemctl start apache2
```
Certbot renews automatically; add `--deploy-hook "systemctl reload apache2"` (or a file in `/etc/letsencrypt/renewal-hooks/deploy/`) so Apache picks up renewed certificates.

## 6. Apache site
```bash
cp deploy/apache-app.conf /etc/apache2/sites-available/billing.conf
nano /etc/apache2/sites-available/billing.conf       # change every line marked EDIT: domain, DocumentRoot, certificate paths
ls /run/php/                                          # make sure the php-fpm socket name in the file matches
a2dissite 000-default
a2ensite billing
apachectl configtest && systemctl reload apache2
```
The vhost redirects HTTP to HTTPS, serves only `public/`, blocks dotfiles, and keeps router tokens out of the access log.

## 7. First administrator and cron
```bash
php bin/create_admin.php "Acme Internet" admin@acme.co.ke 'ChooseAStrongPassword'
cp deploy/billing.cron /etc/cron.d/billing          # check the paths and web user (www-data) inside
```
Open `https://billing.example.com/` and sign in. Five wrong passwords for one email (or thirty failures from one address) lock sign-in from that address for 15 minutes; a lock never extends itself, and the right password works again once it passes. The business name you gave is shown on the login page and the hotspot portal; change it later in **Settings**.

The cron file runs `expire.php` and `monitor.php` every minute, `usage.php` every 5 minutes, `sms.php` every minute (the SMS queue and reminders) and `wg_sync.php` as root every minute (step 8).

## 8. WireGuard hub (routers dial into this)
```bash
./deploy/wireguard-hub.sh billing.example.com
```
This installs WireGuard and nftables, creates the server keys, brings up `wg0` (10.99.0.1) and restricts routers so they may only reach port 8081 on the tunnel address. It **prints the `'wireguard' => [...]` block**: paste it into `config/config.php`, replacing the sample block.

Then serve the router config scripts on the tunnel address only:
```bash
cp deploy/apache-tunnel.conf /etc/apache2/sites-available/billing-tunnel.conf
nano /etc/apache2/sites-available/billing-tunnel.conf   # DocumentRoot and the php-fpm socket
a2ensite billing-tunnel
mkdir -p /etc/systemd/system/apache2.service.d
printf '[Unit]\nAfter=wg-quick@wg0.service\nWants=wg-quick@wg0.service\n' > /etc/systemd/system/apache2.service.d/wg.conf
systemctl daemon-reload && apachectl configtest && systemctl restart apache2
ufw allow 80,443/tcp && ufw allow 51820/udp                 # if you use ufw
ufw allow in on wg0 to 10.99.0.1 port 8081 proto tcp
ufw allow 20000:60000/tcp                                    # remote access ports, see below
ufw route allow in on eth0 out on wg0 to 10.99.0.0/16 proto tcp port 80,8291,8728   # eth0 = your public interface (ip -br a)
```
The `After=` line matters: Apache cannot bind `10.99.0.1:8081` before `wg0` exists, and would fail to start after a reboot.

**Remote access to routers.** Each WireGuard router also gets three public ports on the hub's address: WebFig (router port 80), Winbox (8291) and the API (8728), at `20000 + router id × 10` (+0, +1, +2). **Routers → Connect router** shows them with copy buttons, and They are open to anyone who knows the address, so keep the routers' own admin passwords strong; you can switch each service off per router in **Connect router**. The rules are loaded by the `wg_sync.php` cron job. Use a host name that points at this server for the WireGuard endpoint (for example `vpn.example.com`): it is the address shown to staff. Servers set up before this feature: re-run `deploy/wireguard-hub.sh` once and add the two `ufw` lines.

MikroTik also needs to trust your HTTPS certificate once. The router wizard shows the exact commands. Details: [`PROVISIONING_WIREGUARD.md`](PROVISIONING_WIREGUARD.md).

## 9. Set up the business in the panel
1. **Settings**: brand name and colour, support phone, M-Pesa credentials (use the Daraja sandbox first), the Paybill options, and for GenieACS the ACS URL and parameter preset.
2. **Paybill** (menu): press **Register URLs with Safaricom**, or copy the confirmation and validation URLs shown there into the C2B Register URL request. Customers then pay your Paybill using their account number.
3. **Routers → Add router (WireGuard)**: name it, paste the one command into the router's terminal, wait for "connected", then assign each port (WAN / PPPoE / Hotspot / Static IP) and **Save & apply**.
4. **Plans**: create them; the matching profiles are pushed to the router.
5. **Messages → Gateway** tab: choose Africa's Talking or another HTTP gateway, send a test message, then switch on the automatic messages you want (expiry reminders, expired notice, payment receipts, debt reminders).
6. **Login page designer** (menu): design the page customers see before they pay (colours, logo, texts). The router's `login.html` redirect to it is installed by the router wizard.
7. **Staff & roles**: add technicians and cashiers and adjust their role permissions.

## 10. Check that it all works
```bash
curl -sI https://billing.example.com/ | head -1               # 302 (redirect to login) or 200
php bin/migrate.php --status                                  # every migration "applied"
wg show                                                       # after adding a router: a recent "latest handshake"
php bin/wg_sync.php --dry-run | head                          # shows the peers it would write
tail /var/log/billing-cron.log /var/log/sb-wg-sync.log        # no errors
```
After a reboot, re-run the same checks once to confirm Apache and the tunnel come up in the right order.

## Updating
```bash
cd /var/www/billing
git pull --ff-only
php bin/migrate.php --status        # see what is pending
mysqldump --single-transaction billing > /root/billing-$(date +%F).sql   # back up before migrating
php bin/migrate.php                 # applies only the new migrations, in order, and stops on the first error
systemctl reload 'php*-fpm'         # refresh the PHP opcache
```
A server installed **before** `bin/migrate.php` existed: run `php bin/migrate.php --status`. If every migration has already been applied by hand, run `--baseline` once. Otherwise apply the missing ones manually first, then `--baseline`. MySQL cannot roll back schema changes, which is why the backup comes first.

## Moving from the multi-tenant version
Only needed if you ran the earlier multi-tenant (SaaS) code with data you want to keep.
```bash
mysqldump --single-transaction billing > /root/before-single.sql          # 1. backup
cd /var/www/billing && git pull --ff-only
php bin/convert_to_single.php                                              # 2. dry run: shows what will happen, changes nothing
php bin/convert_to_single.php --yes                                        # 3. convert (one ISP in the database)
php bin/convert_to_single.php --keep=<slug> --yes                          #    several ISPs: keep ONE, the others' data is DELETED
php bin/migrate.php                                                        # 4. add the newer tables (SMS, portal builder)
```
Then remove `base_domain`, `dev_tenant` and `single_tenant` from `config/config.php` (they are ignored) and point your one domain at the site (`public_url`). Existing M-Pesa callback URLs keep working, and routers keep working because their tunnels and API users are unchanged. Replace the old wildcard vhost with `deploy/apache-app.conf` when convenient.

## Backups
Back up daily and keep copies off the server:
- the database: `mysqldump --single-transaction billing | gzip > billing-$(date +%F).sql.gz`
- `config/config.php` (contains `app_key`; without it the encrypted data is unrecoverable)
- `/etc/wireguard/` (`server.key` is baked into every router's tunnel; losing it means re-provisioning every router)

## Troubleshooting
| Symptom | Likely cause |
|---|---|
| Forgot the administrator password, or "Too many failed attempts" | on the server: `php bin/reset_password.php admin@acme.co.ke 'NewStrongPass'` sets a new password and lifts the lock. Other staff can be reset by an administrator in Staff & roles |
| HTTP 500 | `tail /var/log/apache2/billing-error.log`; usually a missing PHP extension (`php -m`) or a wrong DB password |
| Blank or "forbidden" page | `DocumentRoot` is not the `public/` folder, or `AllowOverride All` is missing on it |
| Apache will not start after a reboot | the tunnel vhost starts before `wg0`: check the `After=wg-quick@wg0.service` drop-in from step 8 |
| Router never shows "connected" | UDP 51820 blocked, `wg_sync.php` not running (check `/etc/cron.d/billing`), or the router has no route to the server; look at `wg show` for a handshake |
| Router fetch fails with a certificate error | the router does not trust your HTTPS certificate yet (see the router wizard) |
| STK push works but customers are never activated | M-Pesa callback cannot reach `public_url` (must be public HTTPS) or the Daraja credentials/shortcode are wrong |
| Paybill payments stay "unassigned" | the customer typed an account number that does not exist: assign them by hand on the **Paybill** page |
| SMS stay "queued" | `cron/sms.php` is not running as the web user, the gateway is not set up, or it is outside the allowed hours (Messages → Automatic tab) |
| "Today" income looks shifted | `timezone` in `config/config.php` is wrong |
| ONU WiFi or password change "rejected" | the TR-069 path is wrong for that vendor: open the ONU and use **Detect parameters** |

Nginx instead of Apache: use `deploy/nginx-tunnel.conf` for the tunnel listener and mirror the main-site rules from `deploy/apache-app.conf` (PHP-FPM, no access log for `/provision/`).
