#!/bin/bash
# Installs the monthly investment-bot job (1st of the month, 06:41 local).
# Run once:  bash /var/www/html/finance-tool/install-cron.sh
#
# Idempotent: re-running replaces the existing line rather than adding a second.
# Secrets live in .bot.env (chmod 600, gitignored) so `crontab -l` stays clean.
# The claude CLI carries its own auth, so no ANTHROPIC_API_KEY is needed.
set -euo pipefail
DIR=/var/www/html/finance-tool

# No % anywhere in this prompt on purpose: cron translates an unescaped % into a
# newline, which would truncate the command. The agent runs `date` itself, the
# same way the KoreAI Hermes line does.
PROMPT='Run the autoclawresearch skill for this month. Use the date command for todays date. Gather the pack in ONE run with --market-limit 100 --research --second-opinion, read RULES.md, write the report to reports/market-report-YYYY-MM-DD.md using todays date, following the skill exactly, then deliver it to Discord.'

# `timeout 2h`: a bare cron line has no equivalent of systemd's TimeoutStartSec,
# and this job makes ~10 web searches plus a 100-name Yahoo scan. Without a cap a
# stalled run would sit there until next month's fires on top of it.
LINE="41 6 1 * * set -a; . $DIR/.bot.env; set +a; cd $DIR && timeout 2h /root/.local/bin/claude -p \"$PROMPT\" --dangerously-skip-permissions >> $DIR/cron.log 2>&1"

if [ ! -f "$DIR/.bot.env" ]; then
  echo "ERROR: $DIR/.bot.env is missing. Copy .bot.env.sample, fill it in, chmod 600." >&2
  exit 1
fi

( crontab -l 2>/dev/null | grep -v 'autoclawresearch skill for this month' ; echo "$LINE" ) | crontab -
echo "Installed. Current crontab:"
crontab -l
