# Set and export shell variables for json2file-go

# DEFAULT VALUES
CONFDIR="/etc/json2file-go"
DEFAULT_BASEDIR="/var/spool/json2file-go"
DEFAULT_SOCKDIR="/run/json2file-go"

# DAEMON Variables
cf="basedir"
if [ -f "${CONFDIR}/${cf}" ]; then
    export J2F_BASEDIR="$(head -1 "${CONFDIR}/${cf}")"
else
    export J2F_BASEDIR="${DEFAULT_BASEDIR}"
fi
cf="bind"
if [ -f "${CONFDIR}/${cf}" ]; then
    export J2F_BIND="$(head -1 "${CONFDIR}/${cf}")"
fi
cf="debug"
if [ -f "${CONFDIR}/${cf}" ]; then
    export J2F_DEBUG="$(head -1 "${CONFDIR}/${cf}")"
else
    export J2F_DEBUG=""
fi
cf="dirlist"
if [ -f "${CONFDIR}/${cf}" ]; then
    export J2F_DIRLIST="$(paste -s -d';' "${CONFDIR}/${cf}")"
fi
cf="signature_headers"
if [ -f "${CONFDIR}/${cf}" ]; then
    export J2F_SIGNATURE_HEADERS="$(paste -s -d',' "${CONFDIR}/${cf}")"
fi
cf="token_headers"
if [ -f "${CONFDIR}/${cf}" ]; then
    export J2F_TOKEN_HEADERS="$(paste -s -d',' "${CONFDIR}/${cf}")"
fi
cf="token_fields"
if [ -f "${CONFDIR}/${cf}" ]; then
    export J2F_TOKEN_FIELDS="$(paste -s -d',' "${CONFDIR}/${cf}")"
fi
cf="certfile"
if [ -f "${CONFDIR}/${cf}" ]; then
    export J2F_CERTFILE="$(head -1 "${CONFDIR}/${cf}")"
fi
cf="keyfile"
if [ -f "${CONFDIR}/${cf}" ]; then
    export J2F_KEYFILE="$(head -1 "${CONFDIR}/${cf}")"
fi
cf="host"
if [ -f "${CONFDIR}/${cf}" ]; then
    export J2F_HOST="$(head -1 "${CONFDIR}/${cf}")"
fi
cf="port"
if [ -f "${CONFDIR}/${cf}" ]; then
    export J2F_PORT="$(head -1 "${CONFDIR}/${cf}")"
fi
cf="url_prefix"
if [ -f "${CONFDIR}/${cf}" ]; then
    export J2F_URL_PREFIX="$(head -1 "${CONFDIR}/${cf}")"
fi
cf="socket"
if [ -f "${CONFDIR}/${cf}" ]; then
    export J2F_SOCKET="$(head -1 "${CONFDIR}/${cf}")"
elif [ -z "${J2F_HOST}" ] && [ -z "${J2F_PORT}" ]; then
    export J2F_SOCKET="${DEFAULT_SOCKDIR}/socket"
fi

# Supervisor variables

# Set umask
if [ -n "${J2F_UMASK}" ]; then
    umask "${J2F_UMASK}"
fi
# Create the directory for the socket if it does not exist
if [ -n "${J2F_SOCKET}" ]; then
    RUNDIR="$(dirname "${J2F_SOCKET}")"
    if [ ! -d "${RUNDIR}" ]; then
        if mkdir "${RUNDIR}" 2> /dev/null && [ -n "${J2F_CHUSER}" ]; then
            chown "${J2F_CHUSER}:" "${J2F_CHUSER}" || true
        fi
    fi
fi
