#!/bin/sh
# Source system-wide shell
# start-up script.
# if [ -f /etc/shrc ]; then
#   . /etc/shrc
# fi
# shellcheck disable=SC2249,SC2312
case "$-" in *i*)
  # interactive mode settings go here
  #--- general settings ---
  # 755 file perms
  umask 022
  # no core dumps
  # ulimit -c 0
  # initialize terminal
  eval "$(tset -m ansi:ansi -m "${TERM}":"${TERM:-ansi}" -s -Q)"
  # dont get fancy if we have a dumb terminal
  [ "${TERM}" = 'dumb' ] && return 0
  # control flow bindings
  stty hupcl ixon ixoff -parity
  stty erase "^H" kill "^U" intr "^C" eof "^D"
  # if job control is enabled, set the suspend character
  # to (control-z):
  case $- in
    *m*) stty susp '^z' ;;
  esac
  # colums and tab stops
  #stty cols 80
  tabs -8
  #--- shell options ---
  # vi mode
  set -o vi
  # dont overwrite files with “>"
  set -o noclobber
  # PS command substitions
  # set -o promptcmds
  # print pwd when changed
  #set -o cdprint
  # export variables
  set -o allexport
  # filename completions
  # set -o tabcomplete
  # disable nounset
  set +u
  #--- limits (pub unix only)
  # # files < 512mb
  # ulimit -f 512000
  # # max 250 file descriptors
  # ulimit -S -n 250
  # # max 50 processes
  # ulimit -S -p 50
  # # softlimit 250mb virtual memory
  # ulimit -S -v 250000

  #--- environmental variables ---
  #- (also set ENV="$HOME/.shrc" inside ~/.profile)
  # host
  hup() { (
    read -r pid
    kill -HUP "${pid}"
  ) </var/run/"$1".pid; }
  case "$-" in
    *i*)
      if /bin/test -z "${HOST}"; then
        HOST="$(hostname)"
      fi
      ;;
  esac
  # shell
  SHELL=/bin/sh
  # PS1
  PS1="$(hostname | sed 's/\..*//')"
  case $(id -u) in
    0) PS1="${PS1}:~ # " ;;
    *) PS1="${PS1}:~ $ " ;;
  esac
  # PS2
  PS2='>> '
  # history settings
  if [ -d ~/.history ]; then
    HISTFILE=~/.history/hist.$(tty | sed 's;.*/;;')
    trap 'rm -f $HISTFILE' EXIT
  else
    HISTFILE=~/.history
  fi
  HISTSIZE=1000000
  # editline settings
  EDITRC="${HOME}"'/.editrc'
  export EDITRC
  # path
  if [ "$(id -u)" = 0 ]; then
    PATH=/usr/pkg/sbin:/usr/sbin:/sbin:${PATH}
  else
    PATH=/bin:/usr/bin:/usr/X11R7/bin:/usr/pkg/bin:/usr/local/bin
    PATH=${PATH}:/usr/games:/usr/pkg/java/openjdk8/bin:"${HOME}"'/.bin'
  fi
  # pager settings
  LESS="-ci -P \spacebar\:page ahead b\:page back /\:search ahead \?\:search back h\:help q\:quit"
  export LESS
  # use most?
  #if [ -x /usr/pkg/bin/most ]; then
  #   PAGER='/usr/pkg/bin/most -ds'; export PAGER
  #   else
  #    PAGER="less"; export PAGER
  #fi
  PAGER=less
  # LESSOPEN="|lesspipe.sh %s"
  # LESSCLOSE="lessclose.sh %s %s"
  # colored output (other BSDs)
  # CLICOLOR=yes
  # if [ "$TERM" = cons25 ]; then
  #   LSCOLORS="AxHxcxdxhxefgxAHahBxbx"
  #   else
  #   LSCOLORS="hxHxcxdxAxefgxAHahBxbx"
  # fi

  # encoding
  # LANG="en_US.UTF-8"
  # LC_CTYPE="en_US.UTF-8"

  # user settings
  # USER=$(id -un)
  # UID=$(id -u)
  # GROUP=$(id -ng $USER)
  # MAIL=/var/mail/${LOGNAME}
  # MAILCHECK=1
  # PAPERSIZE=A4
  # BLOCKSIZE=1m
  # GZIP=-9
  # GREP_OPTIONS='-d skip'
  # TERM=xterm-256color
  # EDITOR=nvi
  # VISUAL=${EDITOR}
  # COLORTERM=${TERM}
  # BROWSER=lynx
  # NNTPSERVER="news://retrobsd.ddns.net"

  # mpd
  # MPD_HOST="127.0.0.1"
  # MPD_PORT="6600"
  # MPC_FORMAT="%title% \n%artist% - %album%"

  # X
  # WM=CTWM
  # XCURSOR_THEME="OpenZone_Ice_Slim"
  # GDK_USE_XFT=1
  # GDK_DPI_SCALE=1
  # GDK_SCALE=1
  # QT_XFT=1
  # GTK2_RC_FILES="${HOME}/.gtkrc-2.0"
  # QT_QPA_PLATFORMTHEME=qt5ct
  # QT5DIR=/usr/pkg/qt5
  # MC_XDG_OPEN=xdg-open

  # pkgsrc
  # CVS_RSH=ssh
  # CVSEDITOR=nvi
  # CVSROOT="vins@cvs.NetBSD.org:/cvsroot"
  # MAKECONF=/etc/mk.conf
  # MK_CONF=/etc/mk.conf
  # PKGSRCDIR=/usr/pkgsrc
  #       SIGN_PACKAGES=gpg
  # GPG=/usr/pkg/bin/gpg2
  # GPG_SIGN_AS=PGP_KEY
  # GPG_TTY=$(tty)

  #--- shell functions ---
  # read config
  r() {
    exec ${SHELL} "${HOME%/}"'/.shrc'
  }

  # make dir and go to it
  md() {
    command mkdir -p "$1" && cd "$1" || return
  }

  _cd() {
    # change directory
    dir=$1
    arg=$2
    if [ -n "${arg}" ]; then
      \cd "${dir}" "${arg}" || return
    elif [ -n "${dir}" ]; then
      \cd "${dir}" || return
    else
      \cd || return
    fi
    # set prompt
    dir="${PWD:-$(command pwd -L)}"
    # dir="${dir#${HOME}/}"
    case ${dir} in
      "${HOME}") PS1="~ $ " ;;
      /*) PS1="${PWD} $ " ;;
      *) PS1="${HOME%/}/${dir} $ " ;;
    esac
  }
  # alias cd='_cd'
  eval _cd

  # save to dir stack
  pushd() {
    dirname=$1
    cd "${dirname:?"Missing directory name."}" || return
    DIRSTACK="${PWD} ${DIRSTACK:-${OLDPWD-}}"
    printf '%s' "${DIRSTACK}"
  }
  # change wkrd to top of dir stack
  popd() {
    DIRSTACK=${DIRSTACK#* }
    cd "${DIRSTACK%% *}" || return
    printf '%s' "${PWD}"
  }
  q() {
    printf '%s' "${d}" | sed -Ee "s/'/'\\\\''/g; 1s/^/'/; \$s/\$/'/"
  }
  # change dir interectively
  # courtesy of @rvp at UnitedBSD
  ch() {
    set -- arg dirs d i
    # short-circuit
    if [ $# -eq 0 ]; then
      cd || return
    fi
    arg="$1"
    for d in $(printf '%s' "${arg}" | sed -Ee 's/[^/]+/&*/g'); do
      test -d "${d}" || continue
      dirs="${dirs} $(q "${d}")"
    done
    eval "set -- ${dirs}"
    # no match
    if [ $# -eq 0 ]; then
      printf 1>&2 '%s: %s: no match\n' "$0" "${arg}"
      return 1
    fi
    # single match
    if [ $# -eq 1 ]; then
      cd "$1" || return
    fi
    # multiple matches
    i=0
    for d; do
      i=$((i + 1))
      printf '%d) %s\n' "${i}" "${d}"
    done
    printf '%s\n? ' '-----'
    read -r num
    # do nothing if no number
    if [ "${num}" = "" ]; then
      return 0
    fi
    # invalid number
    if [ "${num}" -lt 1 ] || [ "${num}" -gt $# ]; then
      printf 1>&2 '%s: %s: bad number\n' "$0" "${num}"
      return 1
    fi
    eval "cd \"\${${num}}\""
  }
  # show history
  h() {
    fc -l 1 | sort | uniq
  }
  # clear buffer
  empty() {
    printf "\033[3J"
    # echo $'\e[3J';
  }
  # remove wrkdir, if empty
  rd() {
    dir=${PWD}
    cd ..
    if command rmdir "${dir}" 2>/dev/null; then
      echo 'Removed empty directory:' "${dir}"
    else
      cd "${dir}" || return
      echo 'Directory is not empty:'
      ls -A
    fi
    unset dir
  }
  # remove backup files in the wrkdir
  clean() {
    find . -name \( -name "*.old" -o -name "*.bak" \) -exec sh -c -- 'rm :{}' \;
    find . -size 0 -exec sh -c -- 'rm {}' \;
  }
  # show pid
  pid() {
    # shellcheck disable=SC2009
    ps -e | grep "$@" | cut -d" " -f1
  }
  # move to a dotfile
  dot() {
    for file in "${@-}"; do
      mv -iv "${file}" ."${file}"
    done
  }
  # backup files
  bck() {
    for file in "${@-}"; do
      cp -iv "${file}" "${file}".bak
    done
  }

  # launch tmux
  tm() {
    if [ $# -gt 0 ]; then
      # shellcheck disable=SC2015
      tmux has-session -t "$*" && tmux attach -t "$*" || tmux new-session -s "$*"
    else
      tmux attach || tmux new-session -s default
    fi
  }
  # export tmux session
  tmup() {
    [ -n "${TMUX}" ] \
      && export "$(tmux showenv | grep --color=never '^[^-]' | xargs)"
  }

  # reload process.
  killhup() {
    kill -HUP "$(cat /var/run/"${1}".pid)"
  }

  ssh_copy_id() {
    [ -f ~/.ssh/id_ed25519.pub ] && PK=id_ed25519
    # shellcheck disable=SC2002
    cat ~/.ssh/"${PK}".pub \
      | ssh "$1" "mkdir -p ~/.ssh && cat >>~/.ssh/authorized_keys"
  }

  rmknownhost() {
    [ -z "$1" ] \
      && printf '%s\n' "usage: $(basename "$0") /path/to/known_hosts:line" \
      && return
    ${SED} -i "${1#*:}"d "${1%:*}"
  }

  # extract archives
  ex() {
    if [ -f $1 ]; then
      case $1 in
        *.tar.bz2) tar xjf "$1" ;;
        *.tar.gz) tar xzf "$1" ;;
        *.tar.xz) tar xf "$1" ;;
        *.tar) tar xf "$1" ;;
        *.tar.zst) uzstd "$1" ;;
        *.bz2) bunzip2 "$1" ;;
        *.rar) unrar x "$1" ;;
        *.gz) gunzip "$1" ;;
        *.tbz2) tar xjf "$1" ;;
        *.tgz) tar xzf "$1" ;;
        *.zip) unzip "$1" ;;
        *.Z) uncompress "$1" ;;
        *.7z) 7z x "$1" ;;
        *.deb) ar x "$1" ;;
        *) echo "'$1' cannot be extracted via ex()" ;;
      esac
    else
      echo "'$1' is not a valid file"
    fi
  }

  #--- aliases ---
  alias t='task'
  alias tf='task -f'
  alias tn='task | head -n 1'
  alias pu='ps -fu ${USER-}'
  alias j='jobs'
  alias 1='fg %1'
  alias 2='fg %2'
  alias 3='fg %3'
  alias m='${PAGER}'
  alias lv='ls -laFo'
  alias l='ls -l'
  alias la='ls -aF'
  alias g='egrep -i'
  alias lgrep="ls | egrep -i "
  alias llgrep="ls -l | egrep -i "
  # alias cdl='cd $* && ls'
  cdl() { cd "${*-}" && ls; }
  alias cp='cp -ip'
  alias mv='mv -iv'
  alias rm='rm -i'
  alias ls='ls -F'
  alias df='df -hk'
  alias du='du -hk'
  alias rsz='eval $(resize)'
  alias cls='tput clear'
  alias sane='stty sane'
  alias realpath='readlink -f'
  alias cal='cal -3'
  alias dos2unix="tr -d '\r'"
  ;;
*) ;;
esac
