#!/usr/bin/env bash

if [[ "$EUID" -eq 0 ]]; then
    echo "DO NOT RUN THIS SCRIPT AS ROOT!"
    echo "DO NOT RUN THIS SCRIPT AS ROOT!"
    echo "DO NOT RUN THIS SCRIPT AS ROOT!"
    echo "DO NOT RUN THIS SCRIPT AS ROOT!"
    echo "DO NOT RUN THIS SCRIPT AS ROOT!"
    exit
fi

cd "$(dirname "$0")" || exit

# Office/collector Pis: ethergold-http.service owns port 31234 for OHD.
if systemctl is-enabled ethergold-http.service >/dev/null 2>&1; then
    export ETHERGOLD_HTTP_EXTERNAL=1
fi

mkdir -p ./run ./log

# Keep log.txt bounded — progressive polls and old USBCDC traces can grow without rotation.
LOG_FILE=./log/log.txt
if [[ -f "$LOG_FILE" ]]; then
    log_bytes="$(wc -c < "$LOG_FILE" | tr -d ' ')"
    if [[ "${log_bytes:-0}" -gt 10485760 ]]; then
        tail -n 50000 "$LOG_FILE" > "${LOG_FILE}.tmp" && mv "${LOG_FILE}.tmp" "$LOG_FILE"
        echo "log.txt trimmed to last 50000 lines ($(date))" >> "$LOG_FILE"
    fi
fi

# Best-effort early exit before Python acquires singleton.py lock (authoritative).
if [[ -f ./run/dyzineframe.lock ]]; then
    holder="$(tr -d '\r\n' < ./run/dyzineframe.lock 2>/dev/null || true)"
    if [[ -n "${holder}" ]] && kill -0 "${holder}" 2>/dev/null; then
        echo "DyzineFrame already running (pid ${holder})" >> ./log/log.txt
        exit 1
    fi
fi

(echo -n -e "\n\n\nSTART\n\n\nCurrently running as: $USER - UserID: $(id -u) @ " && date) >> ./log/log.txt 2>&1

# Pi 4-lane CPU policy: pin DF to render core when taskset + nproc>=4 available.
# shellcheck source=cpu_affinity.sh
if [[ -f ./cpu_affinity.sh ]]; then
  # shellcheck disable=SC1091
  source ./cpu_affinity.sh
  if type ohd_df_run >/dev/null 2>&1; then
    ohd_df_run python DyzineFrame.py >> ./log/log.txt 2>&1
    exit $?
  fi
fi
python DyzineFrame.py >> ./log/log.txt 2>&1
