#!/usr/bin/env bash
# PM2 日志策略:关灌屏后的兜底轮转 — 按天保留 3 天,单文件过大也切分.
# 用法(root):
#   bash deploy/pm2_log_policy.sh
#   bash deploy/pm2_log_policy.sh --clean-only
set -euo pipefail

PM2_LOG_DIR="${PM2_LOG_DIR:-/root/.pm2/logs}"
LOGROTATE_CONF="${LOGROTATE_CONF:-/etc/logrotate.d/crypto_monitor_pm2}"
RETENTION_DAYS="${RETENTION_DAYS:-3}"
MAXSIZE="${MAXSIZE:-20M}"
CLEAN_ONLY=0
if [[ "${1:-}" == "--clean-only" ]]; then
  CLEAN_ONLY=1
fi

echo ">>> PM2 log dir: ${PM2_LOG_DIR}"
if [[ ! -d "${PM2_LOG_DIR}" ]]; then
  echo "目录不存在,跳过"
  exit 0
fi

echo ">>> truncate oversized active logs (>20MB) and drop stale files older than ${RETENTION_DAYS}d"
# 当前正在写的大文件用 truncate 清空内容(copytruncate/空写兼容 PM2 仍持有 fd)
find "${PM2_LOG_DIR}" -type f -name '*.log' -size +20M -print -exec truncate -s 0 {} \;
# 过期归档/旧编号日志直接删
find "${PM2_LOG_DIR}" -type f \( -name '*.log' -o -name '*.log.gz' -o -name '*.log.[0-9]*' \) -mtime +"${RETENTION_DAYS}" -print -delete || true

if [[ "${CLEAN_ONLY}" -eq 1 ]]; then
  echo ">>> --clean-only done"
  du -sh "${PM2_LOG_DIR}" || true
  exit 0
fi

echo ">>> install logrotate: ${LOGROTATE_CONF} (daily, rotate ${RETENTION_DAYS}, maxsize ${MAXSIZE})"
cat > "${LOGROTATE_CONF}" <<EOF
${PM2_LOG_DIR}/*.log {
    daily
    rotate ${RETENTION_DAYS}
    maxsize ${MAXSIZE}
    missingok
    notifempty
    compress
    delaycompress
    copytruncate
    dateext
    dateformat -%Y%m%d
}
EOF

# 立即跑一次(不强制等到 cron)
if command -v logrotate >/dev/null 2>&1; then
  logrotate -f "${LOGROTATE_CONF}" || true
else
  echo "warn: logrotate 未安装,仅完成清理;请 apt install logrotate"
fi

echo ">>> size after"
du -sh "${PM2_LOG_DIR}" || true
ls -lah "${PM2_LOG_DIR}" | head -30 || true
echo "done"
