#!/usr/bin/env sh
#
# Determine if term background is dark or light.
# Uses a couple different heuristics, most of them
# from this:
# https://unix.stackexchange.com/questions/245378/common-environment-variable-to-set-dark-or-light-terminal-background
# unix exchange.
#
# If the background is dark, returns exit code 0 (true).
# If the background is light, returns exit code 1 (false).
# TODO implement alternative $COLORBFG method

is_dark() {
	IFS=/ read -r bg_r bg_g bg_b << EOF 
${1:-"0000/0000/0000"}
EOF
	IFS=/ read -r fg_r fg_g fg_b << EOF 
${2:-"ffff/ffff/ffff"}
EOF
    calc=$(echo "($bg_r+$bg_g+$bg_b)-($fg_r+$fg_g+$fg_b)" | tr '[:lower:]' '[:upper:]')
    luminance=$(echo "ibase=16; $calc" | bc)
	if [ "$luminance" -lt 0 ]; then
		true
	else
		false
	fi
}

orig_ssty=$(stty -g)
stty raw -echo min 0 time 0
printf '\e]11;?\a'
sleep 0.01
read -r answer
bg="${answer#*;}"
printf '\e]10;?\a'
sleep 0.01
read -r answer
fg="${answer#*;}"

stty "$orig_ssty"

bg=$(echo "${bg}" | sed 's/.*\(rgb:[0-9a-f/]*\).*/\1/')
fg=$(echo "${fg}" | sed 's/.*\(rgb:[0-9a-f/]*\).*/\1/')

# from the amazing
# https://stackoverflow.com/questions/2683279/how-to-detect-if-a-script-is-being-sourced
# answer
sourced=0
if [ -n "$ZSH_VERSION" ]; then 
  case $ZSH_EVAL_CONTEXT in *:file) sourced=1;; esac
elif [ -n "$KSH_VERSION" ]; then
  # shellcheck disable=SC2296
  [ "$(cd -- "$(dirname -- "$0")" && pwd -P)/$(basename -- "$0")" != "$(cd -- "$(dirname -- "${.sh.file}")" && pwd -P)/$(basename -- "${.sh.file}")" ] && sourced=1
elif [ -n "$BASH_VERSION" ]; then
  (return 0 2>/dev/null) && sourced=1 
else 
  # Detects `sh` and `dash`; add additional shell filenames as needed.
  case ${0##*/} in sh|-sh|dash|-dash) sourced=1;; esac
fi

is_dark "${bg#rgb:}" "${fg#rgb:}"
outp="$?"

if [ "$sourced" -eq 1 ]; then
    if [ "$outp" -eq 0 ]; then
        export TERM_DARK=true
    else
        export TERM_DARK=false
    fi
else
    exit "$outp"
fi