#!/usr/bin/env bash
#
# Publishes scheduled articles whose time has come. deploy.sh adds this to the
# cms user's crontab, every five minutes. Calls the app directly on
# 127.0.0.1, so it works without DNS or HTTPS.
set -euo pipefail

CMS_ROOT="${CMS_ROOT:-/srv/secondline-cms}"
ENV_FILE="$CMS_ROOT/shared/.env"

secret="$(grep -E '^CRON_SECRET=' "$ENV_FILE" | tail -n 1 | cut -d= -f2- | sed -E 's/^"(.*)"$/\1/')"
if [[ -z "$secret" ]]; then
  echo "$(date -u +%FT%TZ) CRON_SECRET is not set in $ENV_FILE" >&2
  exit 1
fi

result="$(curl -fsS --max-time 60 -H "Authorization: Bearer ${secret}" \
  http://127.0.0.1:3200/api/cron/publish-scheduled)"
# Log only when something was published, so the log stays readable.
if ! grep -q '"published":0,' <<<"$result"; then
  echo "$(date -u +%FT%TZ) ${result}"
fi
