#!/usr/bin/env bash
set -euo pipefail
[[ $EUID -eq 0 && $# -eq 2 ]] || { echo 'Usage (root): install-services.sh CPANEL_USER APP_ABSOLUTE_PATH'; exit 1; }
account=$1
app_dir=$2
[[ "$account" =~ ^[a-z][a-z0-9_]{0,31}$ && "$app_dir" =~ ^/home/[a-zA-Z0-9_/-]+$ ]] || { echo 'Invalid user or app path'; exit 1; }
[[ -f "$app_dir/artisan" && -f "$app_dir/.env" ]] || { echo 'Install/configure the application first'; exit 1; }
[[ $(stat -c %U "$app_dir") == "$account" ]] || { echo 'Application must belong to the cPanel account'; exit 1; }
usermod -a -G multiscan "$account"
# Permit only this account (and isolated scanner) to traverse the quarantine.
setfacl -m "u:$account:rwx" /var/lib/multiscan/quarantine
setfacl -d -m "u:$account:rwx" /var/lib/multiscan/quarantine
here=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
for service in multiscan-queue multiscan-scheduler; do
 sed -e "s|@CPANEL_USER@|$account|g" -e "s|@APP_PATH@|$app_dir|g" "$here/systemd/$service.service.in" > "/etc/systemd/system/$service.service"
done
install -m 0644 "$here/systemd/multiscan-scheduler.timer" /etc/systemd/system/
systemctl daemon-reload
systemctl enable --now multiscan-scanner.service multiscan-queue.service multiscan-scheduler.timer
echo 'Restart the domain PHP-FPM pool in WHM to pick up its new supplementary group. Run multiscan:doctor as the account.'
