#!/bin/bash
# ============================================================================
# Wrapper pro jnj_emails_to_fulltext_v1.0.py (JNJ .msg -> Mongo -> PG fulltext).
# Bezi na Unraid hostu, skript spousti uvnitr containeru python-runner.
# Datovane logy + run_latest.log symlink, uklid logu po 30 dnech.
#
# Instalace pres User Scripts plugin nebo /etc/cron.d (zatim NEINSTALOVANO):
#   30 6,18 * * * /mnt/user/Scripts/Janssen_emails_to_fulltext/run_jnj_emails_to_fulltext.sh
# ============================================================================

set -u

BASE_DIR="/mnt/user/Scripts/Janssen_emails_to_fulltext"
LOG_DIR="${BASE_DIR}/logs"
TIMESTAMP=$(date +%Y%m%d_%H%M)
LOG_FILE="${LOG_DIR}/run_${TIMESTAMP}.log"
LATEST_LINK="${LOG_DIR}/run_latest.log"
RETENTION_DAYS=30

mkdir -p "$LOG_DIR"

echo "=== jnj_emails_to_fulltext run @ $(date '+%Y-%m-%d %H:%M:%S') ===" >> "$LOG_FILE"

if ! docker inspect -f '{{.State.Running}}' python-runner 2>/dev/null | grep -q true; then
    echo "ERROR: python-runner container is not running" >> "$LOG_FILE"
    docker start python-runner >> "$LOG_FILE" 2>&1 || exit 1
    sleep 5
fi

docker exec python-runner python /scripts/Janssen_emails_to_fulltext/jnj_emails_to_fulltext_v1.0.py "$@" >> "$LOG_FILE" 2>&1
RET=$?

echo "" >> "$LOG_FILE"
echo "=== Wrapper finished @ $(date '+%Y-%m-%d %H:%M:%S') exit=$RET ===" >> "$LOG_FILE"

ln -sf "$LOG_FILE" "$LATEST_LINK"

find "$LOG_DIR" -name 'run_*.log' -type f -mtime +${RETENTION_DAYS} -delete

exit $RET
