#!/usr/bin/env bash
# Установка cron-агрегатора внешних RSS на web.hhivp.com.
# Запуск:  sudo bash scripts/install-cron.sh
set -euo pipefail

DEPLOY_PATH="${DEPLOY_PATH:-/opt/docker/sites/pushkinohistory-ru-v2}"
DATA_DIR="$DEPLOY_PATH/data"
CRON_FILE="/etc/cron.d/pushkino-rss-aggregator"
LOG_FILE="/var/log/pushkino-rss-aggregator.log"

cd "$DEPLOY_PATH/scripts"
echo "==> installing fast-xml-parser into $DEPLOY_PATH/scripts/node_modules"
sudo -u striker npm install --no-audit --no-fund --omit=dev 2>&1 | tail -3

mkdir -p "$DATA_DIR"
chown striker:docker "$DATA_DIR"
chmod 775 "$DATA_DIR"

cat > "$CRON_FILE" <<EOF
# Pulls external RSS feeds → $DATA_DIR/news.json
# Bind-mounted в контейнер pushkinohistory-ru-v2 как /var/lib/pushkino/data:ro
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# каждый час в 12-ю минуту
12 * * * * striker cd $DEPLOY_PATH && /usr/bin/node scripts/pull-external-rss.mjs >> $LOG_FILE 2>&1
EOF
chmod 644 "$CRON_FILE"

cat > /etc/logrotate.d/pushkino-rss-aggregator <<EOF
$LOG_FILE {
  weekly
  rotate 4
  compress
  delaycompress
  missingok
  notifempty
  copytruncate
}
EOF

systemctl reload cron
echo "==> done. cron file: $CRON_FILE | log: $LOG_FILE"
