#!/bin/sh

# shellcheck disable=SC2312

# set -eu
# shopt -s nullglob

# Trigger error when expanding unset variables
# set -o errexit
# set -o nounset
# set -o xtrace

### Err handling ###
error() {
  err=$?
  case "$1" in
    -e)
      [ -n "${err}" ] || return 0
      shift
      ;;
    *)
      [ "$#" -lt 3 ] && err=-1 || err=$3
      ;;
  esac
  # f=$(readlink -m "$0")
  # echo "Err: ${f/${HOME}/\~}:${1}:(${3:-1}) ${2}"
  exit "${err:?}"
}
trap_errors() {
  # FIXME: even with those options, pkgbuild errors are not catched?
  # [[ $- =~ i ]] && return || exit
  # let shell functions inherit ERR trap.  Same as `set -E' for subshell.
  # see: http://unix.stackexchange.com/questions/48533/exit-shell-script-from-a-subshell
  # set -o errtrace

  #  Trap non-normal exit signals: 1/HUP, 2/INT, 3/QUIT, 15/TERM, ERR
  # BUG: wrong LINENO for correct command
  # MAYBE: used previous LINENO instead of current?
  # ALT:BET?(caller 0):
  # see: https://unix.stackexchange.com/questions/453144/functions-calling-context-in-zsh-equivalent-of-bash-caller
  trap 'error -e ${LINENO} \
    "${FUNCNAME+[$FUNCNAME] }${BASH_COMMAND-}"
    ' HUP INT QUIT TERM
  # see: http://mywiki.wooledge.org/BashFAQ/105

  # NOTE setting ERR trap does implicit `set -o errexit' or `set -e'.
  # NOTE 9/KILL cannot be trapped.
  # NOTE 0/EXIT isn't trapped because:
  #  - with ERR trap defined, trap would be called twice on error
  #  - with ERR trap defined, syntax errors exit with status 0, not 2
}

# NEED: bash>v4.3
_timeout() (
  set +b
  sleep "$1" &
  shift
  "$@" &
  wait
  r=$?
  kill -9 "$(jobs -p)"
  exit "${r}"
)

# ======================== Dirs ======================================
### Go to current script's directory
# BAD:DFL: both realpath and readlink => same path on symlinked script
# ALT: DIR="$(cd "$(dirname "$0")" && pwd)"
# ALT: reliable $(cd "${BIN%/*}" && pwd)/${BIN##*/} BUT:BAD: tailing '/..'
# ALT:FAST: abspath(){ f=$1; case $f in /*) ;; *) f=$PWD/$f ;; esac; printf '%s\n' "$f"; }
# ALSO:(realpath) has --relative-* flags and --strip
#   => normalize path but keep symlinks -- so binary has actual path in $0
# NOTE:WARN:("$0" may be relative):
#   first apply all 'readlink $0' -- and only then do 'cd'

# even around symlinked
cwd_script() { cd "${0%/*}" || return 1; }
# only around original file
cwd_origin() { cd "$(dirname "$(readlink -e "$0")")" || return 1; }
is_empty_dir() { [ -n "$(find "${1:-.}" -maxdepth 0 -type d -empty)" ]; }

dmkdir() {
  [ -d "$1" ] || command mkdir -p "$1" >/dev/null
  # ((700 == $(command stat -c%a "$1"))) || chmod 700 "$1" >/dev/null
  printf '%s\n' "$1"
}
dpwdsfx() { dmkdir "$1/${2:-${PWD##*/}}"; }
dcache() { dpwdsfx "${XDG_CACHE_HOME:-${HOME}/.cache}" "$@"; }
dconfig() { dpwdsfx "${XDG_CONFIG_HOME:-${HOME}/.config}" "$@"; }
dtemp() { dpwdsfx "${TMPDIR:-/tmp}" "$@"; }
drepo() { git -C "${PWD}" rev-parse --show-toplevel; }

# ====================== Configs =====================================
ajoin() {
  IFS="$1"
  shift
  echo "$*"
}
# USAGE:(array) cjoin 'MY_VAR[@]' OR:(verify input): a="${1:?}[@]"
# cjoin() {
#   # set -- ${!1:+"${!1}"}
#   [ -n "$#" ] || return 0
#   printf -- '--ignore '
#   (
#     IFS=,
#     printf '%s\n' "${*// /\\ }"
#   )
# }

# reverse_words() { for ((i = ${#*}; i > 0; i--)); do echo ${!i}; done; }

# hruler() { eval printf '=%.0s' {1.."$(tput cols)"}; }

# shellcheck disable=SC2250
# path_prepend() {
#   for p; do
#     [[ :$PATH: == *:${p/#\~/$HOME}:* ]] || export PATH=$p:$PATH
#   done
# }
path_prepend() {
  case ":$PATH:" in
    *":$1:"*)
      :
      ;;
    *)
      PATH="$1${PATH:+":$PATH"}"
      ;;
  esac
}

# shellcheck disable=SC2249
cfgOpt() {
  IFS=
  case ${CFG_OPTS-} in
    [$*])
      :
      ;;
  esac
} # ALT: [[ ${CFG_OPTS/[$*]} != $CFG_OPTS ]]
# cfgOptAdd() {
#   a=$*
#   o=${CFG_OPTS-}
#   a=${a// /}
#   CFG_OPTS=${o//[$a]/}$a
# }
# ALT:CHECK: cfgOpt ^ab
cfgNo() {
  ! cfgOpt "$@"
}

distro() {
  # ALT: Check distro name and version: lsb_release -si
  # lsb_release -ds 2>/dev/null || cat /etc/*release 2>/dev/null | head -n1 || uname -om
  if [ -e /etc/os-release ]; then
    cat /etc/os-release
  elif [ -e /etc/lsb-release ]; then
    cat /etc/lsb-release
  else
    uname -a
  fi | grep -iqF "$1"
}
die() {
  ret=$?
  if echo "$1" | grep -q '[0-9]+'; then
    ret=$1
    shift
  fi
  [ -n "$#" ] && printf "%s${1+\n}" "$1"
  # for case when you source this functions to interactive shell
  [ -n "${PS1-}" ] && return "${ret}" || exit "${ret}"
}
amAskConfirm() {
  printf '%s' "$1\n"
  read -r answer
  case ${answer} in
    [yY] | [yY][Ee][Ss]) return 0 ;;
    [nN] | [n | N][O | o]) die "Rejected" ;;
    *) die "Invalid input" ;;
  esac
}

Deprecated() {
  ok=1
  for a; do
    if [ -e "${a}" ]; then
      ok=0
      echo "FIX:(remove): ${a}" >&2
    fi
  done
  [ -n "${ok}" ] || exit 5
}

help_from_ifhas() {
  sed -rn '/^(\s*)(el)?if\s+has (\w+)[^;]*;[^#]+#\s*(.*)$/s//\1 -\3  \4/p' "$0"
}
# ALT: $OSTYPE
# get_pltf() {
#   expr substr $(uname -s) 1 5
# }

# ALT: $ id -nu $ OR $ logname $
get_user() {
  echo "${SUDO_USER:-${LOGNAME:-${USER:-${USERNAME:-$(whoami)}}}}"
}
# BUG: on error we can't exit from forked shell and fail main one!
fork_m() {
  if cfgOpt m; then
    eval '"$@" &'
  else
    "$@"
  fi
}
# ====================== Process =====================================

do_sleep() {
  sleep "$1" &
  {
    while kill -0 $! >/dev/null 2>&1; do
      printf "."
      sleep 0.5
    done
    echo
  }
}

has_pr() { hash "$1" >/dev/null 2>&1; } # BET? use builtin "command -v"

# has_lib() {
#   grep -q '^\s*lib'"$1"'\.so\s' <(ldconfig -p);
# }
# has_python() {
#   v=($(python$1 --version 2>&1))
#   [ -d "/usr/lib/python${v[1]%.*}/site-packages/$2" ]
# }
# has_such() {
#   chk=([a]='false' [f]='test -f' [d]='test -d'
#     [P]='has_pkgs' [p]='has_pr' [l]='has_lib'
#     [y]='has_python 3' [Y]='has_python 2'
#   )
#   ${chk[${1:?}]:?} "${2:?}"
# }

# ALT:(running_X broken in raw console?) more stable -- xset q >/dev/null 2>&1
running_X() {
  has_pr X && [ -n "${DISPLAY-}" ] && ! "$(tty)" | grep -q '^/dev/tty'
}
# $(ps opid= -C ${1##*/})
grep_prs() { pgrep "(\/|^)${1##*/}(\s|\$)"; }
kill_prs() {
  pids="$(grep_prs "$1")"
  [ -z "${pids}" ] || kill -TERM "${pids}"
}
run_single() {
  pids
  # to restart programs/reload configs for those which already launched!
  # shellcheck disable=SC2249
  case "$1" in
    -r)
      shift
      kill_prs "$1"
      ;;
  esac
  has_pr "$1" || [ -f "$1" ] || die "Err: no '$1'"
  if ! grep_prs "$1" >/dev/null; then "$@" & fi
}
usvc_run() {
  svc=${1:?No svc}
  shift
  if ! systemctl --user is-enabled "${svc}" >/dev/null 2>&1; then
    "$@"
  elif ! systemctl --user is-active "${svc}" >/dev/null 2>&1; then
    systemctl --user start "${svc}"
  fi
}
# System user for demons without shell access and without a home directory
# == sudo useradd -rUd /dev/null -s /usr/bin/nologin "$1"
add_sysuser() { id -u "${1:?}" >/dev/null 2>&1 || sudo useradd --system --user-group \
  --shell /usr/bin/nologin --home-dir "${2:-/dev/null}" --comment "$1" "$1"; }

## NOTE: usermod adds to multiple groups BUT: unsafe if skip "-a"; gpasswd safe
# but one group only
## https://serverfault.com/questions/688685/usermod-ag-vs-gpasswd-a-as-a-best-practice
# USE: $ id | grep -qwF uinput || sudo gpasswd -a "${LOGNAME:?}" uinput
#   && die "!!! Re-login user session or reboot to update changes in Groups"
# ALT:(id): $ grep -q "uinput.*${LOGNAME:?}" /etc/group
# ALT:(id): $ getent {group|passwd} bitlbee >/dev/null 2>&1
# ALT:(gpasswd): $ sudo usermod -aG uinput "${LOGNAME:?}"
# NEED: relogin/reboot OR $ newgrp uinput OR: apply w/o reboot only for this
# terminal: su - $USER
#   ALT:(newgrp):$ sg uiput -c 'some /bin/sh cmd'
# REM: $ sudo userdel mbsync && sudo groupdel mbsync
# ====================================================================
