# CarePulse IoT — Deployment guide (pilot and production)

Audience: Caresoft DevOps / implementation engineer. Time: half a day for the platform, half a day per hospital site.

## 1. Server
| Item | Pilot (up to ~20 hospitals) | Growth (~100 hospitals) |
|---|---|---|
| App + DB | 1 VPS, 4 vCPU, 8 GB RAM, 160 GB SSD, Ubuntu 24.04 LTS | App: 2 × 4 vCPU / 8 GB behind a load balancer · DB: managed MariaDB/MySQL 8 (8 vCPU / 32 GB) with replica |
| Backups | Second disk or object storage (S3 / Wasabi / Backblaze) via rclone | Same + DB provider snapshots |
| Region | India (DPDP; hospitals expect data in India) | India; separate server for a hospital that requires its own |
| DNS | `app.carepulse.caresoft.co.in` (platform + Level 1), `*.carepulse.caresoft.co.in` (hospital sub-domains), `iot.caresoft.co.in` (website) | |

Waveforms (ICU) are the biggest load: ~1 GB per monitored ICU bed per month at 72 h retention is purged continuously; plan disk for readings (~20 MB per RPM patient per year).

## 2. Operating system hardening
```bash
adduser deploy && usermod -aG sudo deploy           # no root logins
# /etc/ssh/sshd_config: PermitRootLogin no, PasswordAuthentication no (keys only)
ufw allow OpenSSH && ufw allow 80,443/tcp && ufw enable
apt install unattended-upgrades fail2ban && dpkg-reconfigure -plow unattended-upgrades
timedatectl set-timezone Asia/Kolkata
```
Keep MariaDB bound to 127.0.0.1 (or the private network). The edge gateways and apps only need HTTPS (443) to the platform.

## 3. Software
```bash
apt install nginx mariadb-server php8.3-fpm php8.3-{mysql,curl,mbstring,gd,xml,zip,intl} rclone certbot python3-certbot-nginx
mysql_secure_installation
```
**PHP (`/etc/php/8.3/fpm/php.ini`)**: `expose_php = Off`, `display_errors = Off`, `log_errors = On`, `upload_max_filesize = 10M`, `post_max_size = 12M`,
`session.cookie_secure = 1`, `session.use_strict_mode = 1`, `memory_limit = 256M`, `max_execution_time = 60`, `opcache.enable = 1`.

**MariaDB**: `innodb_buffer_pool_size` = 50–60 % of RAM, `max_connections = 300`, `character-set-server = utf8mb4`, `collation-server = utf8mb4_unicode_ci`,
`default-time-zone = '+05:30'` (the app also sets the session time zone).

DB user with rights on the central and every client database (client databases are created automatically when a hospital is added):
```sql
CREATE USER 'carepulse'@'localhost' IDENTIFIED BY '<long random>';
GRANT ALL ON `carepulse\_central`.* TO 'carepulse'@'localhost';
GRANT ALL ON `cp\_client\_%`.* TO 'carepulse'@'localhost';
GRANT ALL ON `cp\_restorecheck\_%`.* TO 'carepulse'@'localhost';   -- weekly restore test
GRANT CREATE ON *.* TO 'carepulse'@'localhost';
GRANT PROCESS ON *.* TO 'carepulse'@'localhost';                    -- mysqldump --single-transaction
```

## 4. Application
```bash
sudo mkdir -p /var/www/carepulse /var/backups/carepulse && sudo chown deploy:www-data /var/www/carepulse
# upload / git pull the release into /var/www/carepulse  (platform/, site/ …)
cd /var/www/carepulse/platform
cp app/config.sample.php app/config.php && chmod 640 app/config.php && chgrp www-data app/config.php
# config.php: app_url, platform_host, env=production, app_key (openssl rand -base64 48), db + client_db,
#             backup_path=/var/backups/carepulse, backup_key (openssl rand -base64 32 – store a copy in the password manager), backup_rclone_remote
php tools/install.php --owner-email=owner@caresoft.co.in --owner-name="Owner Name"
chown -R deploy:www-data storage && chmod -R 770 storage
```
`tools/install.php` is idempotent: run it after every upgrade — it applies central migrations, then every client database migration.

**Nginx** (`/etc/nginx/sites-available/carepulse`):
```nginx
server {
  listen 443 ssl http2; server_name app.carepulse.caresoft.co.in *.carepulse.caresoft.co.in;
  root /var/www/carepulse/platform/public; index index.php; client_max_body_size 12m;
  ssl_certificate /etc/letsencrypt/live/carepulse/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/carepulse/privkey.pem;
  ssl_protocols TLSv1.2 TLSv1.3; server_tokens off;
  location / { try_files $uri /index.php$is_args$args; }
  location ~ \.php$ { include fastcgi_params; fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param HTTP_AUTHORIZATION $http_authorization; fastcgi_read_timeout 120; }
  location ~ /\. { deny all; }
}
server { listen 80; server_name _; return 301 https://$host$request_uri; }
```
TLS: `certbot certonly --manual --preferred-challenges dns -d 'carepulse.caresoft.co.in' -d '*.carepulse.caresoft.co.in'` (wildcard) and
`certbot --nginx -d monitor.<hospital>.com` for each white-label domain. Security headers (CSP, HSTS, frame, nosniff) are sent by the app.

## 5. Scheduled jobs (`crontab -u deploy -e`)
```cron
* * * * *   php /var/www/carepulse/platform/cron/worker.php >> /var/www/carepulse/platform/storage/logs/cron.log 2>&1
0-59/5 * * * * php /var/www/carepulse/platform/tools/monitor.php >> /var/www/carepulse/platform/storage/logs/monitor.log 2>&1
30 2 * * *  php /var/www/carepulse/platform/tools/backup.php >> /var/www/carepulse/platform/storage/logs/backup.log 2>&1
0 4 * * 0   php /var/www/carepulse/platform/tools/restore_check.php >> /var/www/carepulse/platform/storage/logs/backup.log 2>&1
0 3 * * *   find /var/www/carepulse/platform/storage/logs -name '*.log' -size +50M -exec truncate -s 0 {} \;
```
The worker sends messages, runs alert escalation, AI scoring, dose tracking, RTLS checks, maintenance, reports, usage metering and monthly billing.

## 6. Level 1 console — first login
1. `https://app.carepulse.caresoft.co.in/platform/login` → set up the authenticator (mandatory).
2. **Settings**: e-mail (Amazon SES or own SMTP), WhatsApp provider + approved template names (`WHATSAPP_TEMPLATES.md`), SMS, AI key
   (photo reading + AI summary), lead notifications, invoicing / seller details (confirm SAC and GST with the CA).
3. **System health**: alert contacts (e-mail + WhatsApp), copy the health URL into an external uptime monitor (UptimeRobot / Better Stack, 1-minute checks).
   Run **Back up now** and **Test restore** once; both must be green before the first hospital goes live.
4. **Plans**: prices, included messages / calls, add-ons.

## 7. Onboarding a hospital (per site)
1. Level 1 → Clients → + Client (code, plan, quotas, billing details). The client database is created and migrated.
2. Domain: client points `monitor.hospital.com` to the server → add in client → domains → issue the certificate.
3. Hospital admin signs in, sets up 2-step sign-in, then: branding, users and roles, wards and beds, programmes and alert limits
   (medical director signs off), escalation policies, HIS link (`HIS_INTEGRATION.md`), ABDM bridge (`ABDM_BRIDGE.md`).
4. Edge gateway on the hospital network (`EDGE_GATEWAY.md`): pair it, connect monitor gateway HL7, ADT, Modbus devices, BLE RTLS gateways.
5. Devices: register / label, bind to beds or patients; certify device models in the device lab (`DEVICE_CERTIFICATION.md`).
6. Floor maps and tags (`RTLS_SETUP.md`), nurse call (`NURSE_CALL.md`), utilities and maintenance plans (`OPERATIONS_BILLING.md`).
7. Train each role (`TRAINING_PLAN.md`, `manuals/`), then a 2-week supervised pilot with daily review of alerts and AI feedback.

## 8. Go-live checklist (sign off each line)
- [ ] VAPT report closed (no high / critical open) — `SECURITY_VAPT.md`
- [ ] System health all green for 7 days; restore test passed this week; off-site copy present
- [ ] Uptime monitor and alert contacts tested (stop the worker for 11 minutes → message arrives)
- [ ] CDSCO classification opinion received; contracts and UI carry "supports, does not replace, bedside alarms"
- [ ] Medical director approved alert limits, NEWS2 settings, AI thresholds and escalation trees
- [ ] WhatsApp templates approved; SES / SMTP domain has SPF, DKIM, DMARC; DLT for SMS / voice
- [ ] Consent text approved by the hospital (DPDP); privacy notice on the patient portal and app
- [ ] HIS charting tested end-to-end on a test patient; ABDM sandbox passed
- [ ] Every role trained and assessed; quick guides printed for nurse stations
- [ ] Downtime procedure agreed: if CarePulse is down, bedside monitors and paper charting continue; who calls whom

## 9. Upgrades and rollback
1. Announce the window (low-traffic, e.g. 14:00–15:00 IST) to hospital admins.
2. `php tools/backup.php` (fresh set) → deploy the new release to a new folder → copy `app/config.php` and `storage/` link → switch the symlink
   `/var/www/carepulse → releases/<version>` → `php tools/install.php` → reload php-fpm.
3. Smoke test: `/api/v1/health`, Level 1 → System health, one hospital dashboard, one API reading.
4. Rollback: switch the symlink back. Database migrations only add tables/columns; if one must be reverted, restore the pre-upgrade backup set.

## 10. Disaster recovery
* **RPO** 24 h (nightly backup; increase to hourly binlog shipping for large hospitals) · **RTO** 4 h.
* New server → steps 2–5 → restore: for each `*.sql.gz.enc`: `openssl enc -d -aes-256-cbc -pbkdf2 -iter 200000 -pass env:CP_BACKUP_KEY -in X | gunzip | mysql <db>`;
  `storage.tar.gz.enc` → decrypt → `tar -xzf - -C platform/storage` → `php tools/install.php` → update DNS.
* Edge gateways and apps queue data while the platform is unreachable and resend automatically (edge: days; apps: until sent).
