#!/bin/sh
# Installs ALL billing cron jobs into /etc/cron.d/billing. Safe to run again (it replaces the file).
#   sudo sh bin/install_cron.sh                      # app in /var/www/billing, web user www-data
#   sudo sh bin/install_cron.sh /srv/radius apache   # another app path / web user
# Needs: root. Writes /etc/cron.d/billing and creates /var/log/billing-cron.log.
set -eu
APP="${1:-/var/www/billing}"; WEBUSER="${2:-www-data}"; OUT="${CRON_OUT:-/etc/cron.d/billing}"
SRC="$(cd "$(dirname "$0")/.." && pwd)/deploy/billing.cron"
[ -f "$SRC" ] || { echo "cannot find $SRC" >&2; exit 1; }
id "$WEBUSER" >/dev/null 2>&1 || { echo "user $WEBUSER does not exist" >&2; exit 1; }
# swap the app path everywhere, and the web user on every line that is not the root-only WireGuard job
sed -e "s#/var/www/billing#$APP#g" \
    -e "/wg_sync\.php/! s#^\([-0-9*/, ]* [-0-9*/, ]* [-0-9*/, ]* [-0-9*/, ]* [-0-9*/, ]*\)  *www-data #\1 $WEBUSER #" \
    "$SRC" > "$OUT.tmp"
chmod 644 "$OUT.tmp"; mv "$OUT.tmp" "$OUT"
touch /var/log/billing-cron.log /var/log/sb-wg-sync.log; chown "$WEBUSER" /var/log/billing-cron.log 2>/dev/null || true
echo "Installed $(grep -c 'php ' "$OUT") cron jobs in $OUT (app $APP, user $WEBUSER):"; grep -o 'php [^ ]*' "$OUT"
