#!/bin/ksh
#
# initialization script for interactive ksh(1) sessions.

# shellcheck disable=SC1090
# . "${HOME}/.profile"
[ -f ~/.profile ] && . ~/.profile
# [ -f ~/.rc ] && . ~/.rc

# reload a running shell session
reload() {
  . ~/.kshrc
}

# clear with ctrl+l
# bind -m '^L'=clear'^J'
bind -m ='clear'^J

PS1='$(tput bold)$(pwd | sed s:${HOME}:~:) \$$(tput sgr0) '

alias ta='tmux attach -t 0'
# alias vpn_up='doas wg-quick up /etc/wireguard/vpn.conf'
# alias vpn_down='doas wg-quick down /etc/wireguard/vpn.conf'
# alias top='htop -C'
# alias less='less --no-vbell'
# alias wget='wget --no-hsts'
# alias blog='less ${HOME%/}/doc/people/blogroll'
# alias duck='w3m -no-graph duckduckgo.com'

# alias autoload='typeset -fu'
# alias functions='typeset -f'
# alias hash='alias -t'
# alias history='fc -l'
# alias integer='typeset -i'
# alias local='typeset'
# alias login='exec login'
# alias newgrp='exec newgrp'
# alias nohup='nohup '
# alias r='fc -e -'
# alias stop='kill -STOP'
# alias suspend='kill -STOP $$'
# alias type='whence -v'
# alias x='exit'

# depends only on OpenBSD base utilities.
# extend doas to re-run previous command on doas when no argument is given
# doas() {
#   # shellcheck disable=SC2312
#   case "$#" in
#     0)
#       fc -e "sed -i '/^doas/!s/^/doas /'" "$(
#         fc -l 1 \
#           | sed -En '
#         /^[[:digit:]]+[[:space:]]+doas/!h
#         ${
#           g
#           s/[[:space:]].*//
#           p
#         }
#       '
#       )"
#       ;;
#     *)
#       command doas "$@"
#       ;;
#   esac
# }
# alias doas='doas '
# alias fuck='doas '

# extend cd with two forms for going up; and set completions for make(1)
cd() {
  case "$#" in
    0) set -- "${HOME}" ;;
    1) ;;
    *) set -- "$*" ;;
  esac
  # shellcheck disable=SC2249,SC3002
  case "$1" in
    .+(.)?(/*))
      # go up this much dots, then to PATH:   cd ..../foo/bar
      set -- "$1" "${PWD}"
      while true; do
        case "$1" in
          ..*) set -- "${1#.}" "${2%/*}" ;;
          *) break ;;
        esac
      done
      set -- "$2/${1#*/}"
      ;;
    ..*)
      # go up to first directory with NAME:   cd ..NAME
      set -- "${PWD%"${PWD##*"${1#".."}"}"}"
      ;;
  esac
  command cd "$1" >/dev/null || return 1
  # shellcheck disable=SC2046,SC2312,SC3041
  set -A complete_make -- $(
    exec 2>/dev/null
    timeout 1s make -qp \
      | sed -n '/^[A-Za-z][^ :]* *:/{s/\([^: ]*\).*/\1/p;}'
  )
  case "${PWD}/" in
    "${HOME}"/*)
      printf "%s\n" "~${PWD#"${HOME}"}"
      ;;
    *)
      printf "%s\n" "${PWD}"
      ;;
  esac
  return 0
}

# Further functions do not modify the currently running shell session.
#
# From now on, i define functions in a subshell like `f()(...)`, rather
# than in the current shell like `f(){ ...;}`.  Thus, all variables are
# local; and built-ins like exec, exit, and trap behave like they would
# in a shell script.

# spawn command in background, ignoring output
nohup() (
  trap : HUP
  exec 1>/dev/null 2>/dev/null 0</dev/null
  exec "$@" &
)

# read stdin into temp file; run args on file; write file to stdout
pee() (
  test "$#" -eq 0 && set -- cat
  temp=
  trap '\rm -f -- "$temp"' EXIT
  temp="$(mktemp)"
  test -n "${temp}" && test -w "${temp}" && test -r "${temp}" || {
    rm "${temp}" 2>/dev/null
    return 1
  }
  cat >"${temp}" && "$@" "${temp}" <>/dev/tty >&0 2>&0 && cat "${temp}"
)

# completions; ignore error when defining them
# {
#   set -A complete_sysctl \
#     $(sysctl | sed 's,[= ].*,,')
#   set -A complete_rcctl \
#     $(rcctl ls all)
#   set -A complete_vmctl \
#     $(vmctl status | awk '!/NAME/{print $NF}')
#   set -A complete_rcctl_1 \
#     disable enable get ls order set restart start stop
#   set -A complete_vmctl_1 \
#     console create load log pause receive reload reset \
#     send show start status stop unpause wait
#   set -A complete_got_1 \
#     add backout blame branch cat checkout cherrypick clone \
#     commit diff fetch histedit import info init integrate \
#     log merge patch rebase ref remove revert send stage \
#     status tag tree unstage update
#   set -A complete_mpc_1 \
#     add addplaylist albumart cdprev channels clear \
#     clearerror clearplaylist consume crop crossfade current \
#     del delpart delplaylist disable enable find findadd idle \
#     idleloop insert list listall listneighbors load ls \
#     lsdirs lsplaylists makepart mixrampdb mixrampdelay mount \
#     move moveoutput moveplaylist next outputs outputset \
#     partitions pause pause-if-playing play playlist prev \
#     prio queued random readpicture renplaylist repeat \
#     replaygain rescan rm save search searchadd searchplay \
#     seek seekthrough sendmessage shuffle single stats \
#     sticker stop subscribe toggle toggleoutput unmount \
#     update version volume waitmessage
# } 2>/dev/null

# force emacs[1] keybindings even when $VISUAL is set to a vi-like editor
# [1]: That's actually UNIX keybindings; see <https://unix-kb.cat-v.org>.
# set -o emacs
# shellcheck disable=SC3040
set -o braceexpand
bind '^H'=delete-word-backward

# history
FCEDIT="${VISUAL:-${EDITOR:-"vi"}}"
export HISTFILE="${HOME}/.local/state/ksh_history"
HISTSIZE=10000
HISTCONTROL=ignoredups
alias history="fc -l 1"
alias redo="fc -e :"
alias reset="tput reset"

# file management (be verbose and interactive)
#alias rm='rm -vi'
alias rm='trash'
alias mv='mv -vi'
alias cp='cp -iR'
alias mkdir='mkdir -p'

# binary file dump
alias hexdump='hexdump -C'
alias od='od -cAx'

# human-readable sizes
alias df='df -h'
alias du='du -hc'
alias ls='ls -1ph'
alias disklabel='disklabel -h'

# lazyman aliases
alias lc='ls -C'
alias ll='ls -l'
alias la='lc -A'
alias calc='bc -l'
alias igrep='fgrep -i'

# commands with command as argument (for futher alias expension)
alias xargs='tr "\n" "\0" | xargs -0 '
alias timeout='timeout '
alias apply='apply '

# pipeline utils
# PROTIP: Running "doas foo >/root/file" does not write into /root/file.
#         If that's what you want; use "foo | doas save secret" instead.
# PROTIP: Use "doas cat secret | foo" rather than "doas foo secret" for
#         priviledge separation (useless cat is not useless).
# PROTIP: Use "foo | see | bar" to see what is going on in the pipeline.
# PROTIP: Avoid redirection operators (<, >, >>) on interactive shells!
alias overwrite='save -f --'
alias append='save -a --'
alias saveas='save -b --'
alias see='tee /dev/tty'
alias vee='pee "${EDITOR:-"${VISUAL:-"vi"}"}" --'
# shellcheck disable=SC2154
alias lee='pee "${PAGER:-"less"}" --'

# typos
alias mkae='make'
alias makemake='make'

# etc
alias diff='diff -up'

# prompt is "\n HOST ❯ " (red if root; HOST if ssh; also set window title)
PS1='$(
  case "$(id -u)" in
    (1000) user="" ;;
    (*) user="$USER@"    ;;
  esac
  case "$PWD/" in
    ("$HOME"/*) cwd="~${PWD#"${HOME}"}" ;;
    (*)         cwd="$PWD"              ;;
  esac
  term='"$(tty | sed s,^/dev/,,)"'
  host='"${SSH_CONNECTION:+"$(hostname)"}"'
  title="$host${host:+:}$cwd - $term"
  printf "\e[0m\e]0;%s\a\n\e[31m%s%s ❯ \e[0m" "$title" "$user" "$host"
)'

# 2nd prompt is " ❮ " (red if root, white otherwise)
PS2="$(
  printf "\e[0m \e[31m❮ \e[0m"
)"

# print last command's exit status, if non-zero
trap 'printf "\e[31mEXIT: %s\e[0m\n" "$?"' ERR

# run cd function above just to set completion for make(1)
cd . >/dev/null 2>&1

export GPG_TTY="$(tty)"
