#!/bin/bash

set -eu

SETMAN_COMPONENT=${SETMAN_COMPONENT:-setman}

SETMAN_LOG_WRITE_TO_JOURNAL="${SETMAN_LOG_WRITE_TO_JOURNAL:-1}"
SETMAN_LOG_WRITE_TO_STDERR="${SETMAN_LOG_WRITE_TO_STDERR:-0}"
SETMAN_LOG_CAPTURE_FILE="${SETMAN_LOG_CAPTURE_FILE:-}"

get_severity() {
    local severity=$1
    case ${severity} in
        critical)
            severity=crit
            ;;
        error)
            severity=err
            ;;
        warn)
            severity=warning
            ;;
    esac

    valid_severity_levels=(emerg alert crit err warning notice info debug)
    if echo ${valid_severity_levels[@]} | grep -qw "${severity}"; then
        echo ${severity}
    else
        echo "notice"
    fi
}

show_usage()
{
    echo "setman-log <severity> [<options>] [message...]"
    echo
    echo "  Supported <severity> levels are from syslog standard:"
    echo "    emerg:         system is unstable"
    echo "    alert:         action must be taken immediately"
    echo "    crit|critical: critical conditions"
    echo "    err|error:     error conditions"
    echo "    warn|warning:  warning conditions"
    echo "    notice:        normal but significant conditions"
    echo "    info:          informational messages"
    echo "    debug:         debug-level messages"
    echo "  An unknown <severity> value is treated as notice."
    echo
    echo "  Options:"
    echo "    --notify       messages forwarded to user (not implemented yet)"
    echo "    --help         show this help"
}

severity=""
message=()
notify_user=0
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_usage
            exit 0
            ;;
        --notify)
            notify_user=1
            shift
            ;;
        -*|--*)
            echo "Unknown option: $1"
            exit 1
            ;;
        *)
            if [[ "${severity}" == "" ]]; then
                severity=$(get_severity $1)
            else
                message+=("$1")
            fi
            shift
    esac
done

if [[ -z "${severity}" ]]; then
    echo "missing required argument: <severity>"
    exit 1
fi

if [[ -z "${message[@]}" ]]; then
    echo "missing argument: <message>..."
    exit 1
fi

full_message="${SETMAN_COMPONENT}: ${message[@]}"

if [[ "${notify_user}" == "1" ]]; then
    echo "${full_message}" >> notify-output
fi

if [[ -n "${SETMAN_LOG_CAPTURE_FILE}" ]]; then
    echo "${full_message}" >> ${SETMAN_LOG_CAPTURE_FILE}
fi

if [[ ${SETMAN_LOG_WRITE_TO_STDERR} == 1 ]]; then
    important_severity_levels=(emerg alert crit err warning)
    if echo ${important_severity_levels[@]} | grep -qw "${severity}"; then
        echo "${full_message}" >&2
    fi
fi

if [[ ${SETMAN_LOG_WRITE_TO_JOURNAL} == 1 ]]; then
    # -p stands for priority. BusyBox logger knows only `-p` form
    logger -p "user.${severity}" "${full_message}"
fi
