#!/usr/bin/env bash
#
# Power an icon for tinting the screen at night.
set -euo pipefail
IFS=$'\n\t'
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

SLEEP_INTERVAL=${SLEEP_INTERVAL:-30}

# ◓◒●◌◎
# 🔴🔵🟠🟡🟢🟣🟤
# 🟥🟦🟧🟨🟩🟪🟫
# ☀☯⭐🌝🌞⏾
# 🌑🌓🌗🌕
# 👓

############## Setup #########################

function cleanup {
    log "Killing child process $wlsunset_pid"
    kill "$wlsunset_pid"
    true
}
for sig in EXIT; do
  trap "set +e; cleanup" "$sig"
done

function die {
    local status_code="$1"
    shift
    (>&2 echo "${@}")
    exit "$status_code"
}

function log {
    (>&2 echo "${@}")
}

############## Program #########################

function main {
    local night_mode_icon night_mode_text night_mode_class
    night_mode_mode="auto"
    night_mode_class=""
    wlsunset -S 07:00 -s 22:00 &
    wlsunset_pid=$!

    while true; do
        if [ "$night_mode_mode" == "auto" ]; then
            night_mode_icon="🌗"
            night_mode_text="auto"
        elif [ "$night_mode_mode" == "on" ]; then
            night_mode_icon="🌑"
            night_mode_text="night"
        elif [ "$night_mode_mode" == "off" ]; then
            night_mode_icon="🌕"
            night_mode_text="day"
        fi

        render
        sleep "$SLEEP_INTERVAL" &
        wait $! || true
    done
}

function render {
    jq --unbuffered --compact-output <<EOF
{
"text":"${night_mode_icon}",
"tooltip":"${night_mode_text}",
"percentage":100,
"class":"${night_mode_class}"
}
EOF
}

function handle_click {
    if [ "$night_mode_mode" == "auto" ]; then
        log "Setting night mode to force-day."
        night_mode_mode="off"
    elif [ "$night_mode_mode" == "on" ]; then
        log "Setting night mode to auto."
        night_mode_mode="auto"
    elif [ "$night_mode_mode" == "off" ]; then
        log "Setting night mode to force-night."
        night_mode_mode="on"
    fi
    kill -s SIGUSR1 "$wlsunset_pid"
}

trap "handle_click" SIGUSR1

main "${@}"
