#!/bin/sh

# PROVIDE: tag_albums
# REQUIRE: LOGIN NETWORKING
# KEYWORD: shutdown
#
# Add to /etc/rc.conf:
#   tag_albums_enable="YES"
# Optional:
#   tag_albums_runas="tagalbums"
#   tag_albums_dir="/usr/local/tag-albums"          # checkout, with .venv from `uv sync`
#   tag_albums_env_file="/usr/local/etc/tag_albums.env"
#   tag_albums_port="8087"
#
# The service logs to syslog with the tag "tag_albums".

. /etc/rc.subr

name="tag_albums"
rcvar="tag_albums_enable"

load_rc_config $name

: ${tag_albums_enable:="NO"}
: ${tag_albums_runas:="tagalbums"}
: ${tag_albums_dir:="/usr/local/tag-albums"}
: ${tag_albums_env_file:="/usr/local/etc/tag_albums.env"}
: ${tag_albums_port:="8087"}

# daemon(8) runs as root to write the pidfile, supervises and restarts the
# service, and drops privileges to ${tag_albums_runas} for the child.
pidfile="/var/run/${name}.pid"
procname="daemon"
command="/usr/sbin/daemon"
command_args="-S -T ${name} -P ${pidfile} -r -u ${tag_albums_runas} \
    ${tag_albums_dir}/.venv/bin/tag-albums serve --port ${tag_albums_port}"

start_precmd="${name}_prestart"

tag_albums_prestart()
{
    if [ ! -r "${tag_albums_env_file}" ]; then
        err 1 "${tag_albums_env_file} is missing (needs API_TOKEN, HA_URL, HA_TOKEN, DB_PATH)"
    fi
    # Export the settings to the service's environment.
    set -a
    . "${tag_albums_env_file}"
    set +a
}

run_rc_command "$1"
