#!/usr/bin/env bash
# Log rotation for corp-leisure (LEIS-1048). Run ONCE on the production server, as the
# user that runs pm2:
#
#     bash scripts/setup-pm2-logrotate.sh
#
# Without it, logs/pm2-*.log (see ecosystem.config.js) grow forever and eventually fill
# the disk. The app now writes one JSON line per API request, so they grow faster than
# before.
#
# Compression is deliberately NOT set. pm2-logrotate 3.0.0 ignores `compress`: `pm2 set` stores
# the value as the string "true", the module's helper library (pmx) casts it to a real boolean,
# and the module then tests `=== 'true'`, which a boolean never matches. Verified: with compress
# set, rotated files were still plain .log. Rotation and `retain` do work (verified on pm2 5.4.3).
# Disk bound: each log is capped near max_size and `retain` rotated copies are kept, and the app
# writes pm2-out.log and pm2-combined.log with the same lines, so plan for roughly
# (retain + 1) x max_size x 2 per app, about 1.5 GB at these settings.
#
# pm2-logrotate is a pm2 module: it rotates the log files of every app pm2 manages,
# including the custom paths set in ecosystem.config.js (error_file / out_file /
# log_file), so no per-app config is needed. The settings below are the module's own;
# change them with `pm2 set pm2-logrotate:<key> <value>`.
#
#   max_size        rotate when a file passes 50 MB (or at the interval, whichever is first)
#   retain          keep 14 rotated files per log
#   rotateInterval  also rotate every day at midnight (server time)
#   workerInterval  how often the module checks sizes, in seconds
set -euo pipefail

if ! command -v pm2 >/dev/null 2>&1; then
  echo "pm2 is not installed or not on PATH" >&2
  exit 1
fi

pm2 install pm2-logrotate

pm2 set pm2-logrotate:max_size 50M
pm2 set pm2-logrotate:retain 14
pm2 set pm2-logrotate:dateFormat YYYY-MM-DD_HH-mm-ss
pm2 set pm2-logrotate:workerInterval 30
pm2 set pm2-logrotate:rotateInterval "0 0 * * *"
pm2 set pm2-logrotate:rotateModule true

# Survive a server reboot: pm2 resurrects the module along with the app.
pm2 save

echo
echo "pm2-logrotate configured:"
pm2 conf pm2-logrotate
