#!/bin/bash
set -e

# Timestamp and log file
TS=$(date +"%Y-%m-%d_%H-%M-%S")
LOG="/home/orangepi/FOXSI5_Flight/Logs/Startup_Logs/tpx3X4_crontab_startup_${TS}.log"

# Wait for network/board to settle, changed from  to 5
sleep 5

export PYTHONPATH=/home/orangepi/FOXSI5_Flight/StaticFiles:$PYTHONPATH

# Run the main startup shell script
echo "[$(date)] Starting tpx3X4 startup script" >> "$LOG"
/home/orangepi/FOXSI5_Flight/Startup/tpx3X4_startup.sh >> "$LOG" 2>&1
EXIT_CODE=$?

if [ $EXIT_CODE -eq 0 ]; then
    echo "[$(date)] Startup script finished successfully (exit=$EXIT_CODE)" >> "$LOG"
else
    echo "[$(date)] Startup script FAILED (exit=$EXIT_CODE). Skipping Python scripts. Request PowerCycle." >> "$LOG"
    exit $EXIT_CODE
fi

# Short pause before starting Python scripts --> changed from 10 seconds to 5
sleep 5

# Start Formatter_OP_FOXSI5_TPX.py in background with timestamped logging
echo "[$(date)] Starting Formatter_OP_FOXSI5_TPX.py (background)" >> "$LOG"
/usr/bin/python3 /home/orangepi/FOXSI5_Flight/Startup/Formatter_OP_FOXSI5_TPX.py 2>&1 | \
    awk '{ print strftime("[%Y-%m-%d %H:%M:%S]"), $0; fflush(); }' >> "$LOG" &

# Start FOXSI5_UDP_reader.py in background with timestamped logging
echo "[$(date)] Starting FOXSI5_UDP_reader.py (background)" >> "$LOG"
/usr/bin/python3 /home/orangepi/FOXSI5_Flight/Startup/FOXSI5_UDP_reader.py 2>&1 | \
    awk '{ print strftime("[%Y-%m-%d %H:%M:%S]"), $0; fflush(); }' >> "$LOG" &

echo "[$(date)] Crontab startup sequence complete" >> "$LOG"
