#!/usr/bin/env bash
# install-cron.sh — installs the emergence cycle on the self-hosted remote: every 2 hours UTC,
# pull both repos, run one pipeline cycle (--commit), log to ~/logs/emergence.log.
# The Mac is dev only; the canonical net runs on the self-hosted remote.

set -euo pipefail

REMOTE_HOST="${REMOTE_HOST:-remote}"

ssh "$REMOTE_HOST" 'set -e
  mkdir -p ~/logs ~/coherence/fact.ngo
  cd ~/coherence/fact.ngo
  for r in emergence emergence-data; do
    if [ ! -d $r/.git ]; then
      git clone -q ~/remotes/fact.ngo/$r.git $r
      git -C $r config user.name zauh && git -C $r config user.email zauh@coherence.ngo
    else
      git -C $r pull -q
    fi
  done
  mkdir -p ~/bin
  cat > ~/bin/emergence-cycle.sh <<EOF
#!/usr/bin/env bash
set -uo pipefail
cd ~/coherence/fact.ngo/emergence
git pull -q
export EMERGENCE_DATA=\$HOME/coherence/fact.ngo/emergence-data
node scripts/pipeline.js --commit >> ~/logs/emergence.log 2>&1
EOF
  chmod +x ~/bin/emergence-cycle.sh
  crontab -l 2>/dev/null | grep -v "emergence-cycle.sh" > /tmp/cron.new || true
  echo "7 */2 * * * \$HOME/bin/emergence-cycle.sh" >> /tmp/cron.new
  crontab /tmp/cron.new
  rm /tmp/cron.new
  echo "cron installed:"; crontab -l | grep emergence'

echo "emergence cron: every 2h on the self-hosted remote. logs: remote:~/logs/emergence.log"
