#!/command/with-contenv bash
# shellcheck shell=bash
# Start the Frigate service

set -o errexit -o nounset -o pipefail

# $HOME is /root from the container env and survives s6-setuidgid, so cache
# and telemetry writes (huggingface, openvino) fail after the drop. Set it
# before opt_in_out so the opt-out marker lands where the service will look.
if [[ "${FRIGATE_RUN_AS_ROOT:-false}" != "true" ]]; then
    export HOME=/config
fi

# opt out of openvino telemetry
if [ -e /usr/local/bin/opt_in_out ]; then
  /usr/local/bin/opt_in_out --opt_out > /dev/null 2>&1
fi

# Logs should be sent to stdout so that s6 can collect them

# Tell S6-Overlay not to restart this service
s6-svc -O .

function set_libva_version() {
    local ffmpeg_path
    ffmpeg_path=$(python3 /usr/local/ffmpeg/get_ffmpeg_path.py)
    LIBAVFORMAT_VERSION_MAJOR=$("$ffmpeg_path" -version | grep -Po "libavformat\W+\K\d+")
    export LIBAVFORMAT_VERSION_MAJOR
}

echo "[INFO] Preparing Frigate..."
set_libva_version

echo "[INFO] Starting Frigate..."

cd /opt/frigate || echo "[ERROR] Failed to change working directory to /opt/frigate"

# Replace the bash process with the Frigate process, redirecting stderr to stdout
exec 2>&1
if [[ "$(id -u)" -ne 0 || "${FRIGATE_RUN_AS_ROOT:-false}" == "true" ]]; then
    exec python3 -u -m frigate
else
    exec s6-setuidgid frigate python3 -u -m frigate
fi
