#!/bin/bash

[[ "$TRACE" ]] && set -x
set -eo pipefail

function random_word()
{
    egrep -x '[a-z]+' /usr/share/dict/words | shuf -n 1 --random-source=/dev/urandom
}

for alert_functions in $(ls /usr/share/dirty-orange/alert.d/*.sh); do
    source "$alert_functions"
done

function write_log()
{
    log_file="/var/log/dirty-orange/alerts.log"
    ts=$(date '+%Y-%m-%d %H:%M:%S')
    echo "$ts $@" >> "$log_file"
}

function set_alert()
{
    name=$1
    value=$2
    alert_path="/var/dirty-orange/alerts/$name"
    echo -n "$value" > "$alert_path"
}

function fix_alert()
{
    name=$1
    alert_path="/var/dirty-orange/alerts/$name"
    [[ -f "$alert_path" ]] || { echo "No alert named $name"; return 1; }

    alert_timer_path="/var/dirty-orange/alert_timers/$name"
    [[ -f "$alert_timer_path" ]] && { echo "Alert timer for $name already exists"; return 1; }

    fix_duration=$(<"$alert_path")
    now=$(date +%s)
    let expires_at="$now"+"$fix_duration"
    echo -n "$expires_at" > "$alert_timer_path"
    echo "It takes you $fix_duration seconds to fix this alert.
        Until $(date -d @$expires_at) you should react to other incoming
        alerts as if you were busy fixing this one."
}

function reap()
{
    if returns_ok /hey; then
        echo 0 > /var/dirty-orange/alerts/5xx
    else
        echo 1 > /var/dirty-orange/alerts/5xx
    fi

    now=$(date +%s)
    for timer in $(ls /var/dirty-orange/alert_timers); do
        timer_path="/var/dirty-orange/alert_timers/$timer"
        expires_at=$(<"$timer_path")
        if (( $expires_at < $now )); then
            set_alert "$timer" 0
            write_log "alert $timer expired"
            rm "$timer_path"
        fi
    done
}

function is_predefined()
{
    [[ -x "/usr/share/dirty-orange/alert.d/$1.sh" ]]
}

function control_alert()
{
    action=$1
    alert=$2
    if [[ $alert == "${QLOUD_APPLICATION}_${QLOUD_ENVIRONMENT}_disk_usage" ]]; then
        alert="unispace"
    fi
    if is_predefined "$alert"; then
        ${alert}_${action} ${@:3}
    else
        case "$action" in
            start)
                set_alert "$alert" "$3"
                ;;
            stop)
                set_alert "$alert" 0
                ;;
            fix)
                fix_alert "$alert"
                ;;
        esac
    fi
    write_log "alert $alert ${action}ed"
}

function usage()
{
    echo 'alertctl start|stop|fix <name>'
}

case "$1" in
    -h | --help)
        usage
        ;;
    start | stop | fix)
        control_alert $@
        ;;
    reap)
        reap
        ;;
    *)
        usage
        exit 1
        ;;
esac
