#!/bin/ksh
#
# Initialization script for interactive ksh(1) sessions.
# Depends only on OpenBSD base utilities.
#
# © 2025 Lucas de Sena <lucas at seninha dot org>.
# No rights reserved.  Dedicated into Public Domain.  Use as you will.
# THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY (works on my machine™)

. "$HOME/.profile"

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

# extend doas to re-run previous command on doas when no argument is given
doas() {
	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
}

# extend cd with two forms for going up; and set completions for make(1)
cd() {
	case "$#" in
	(0) set -- "$HOME" ;;
	(1)                ;;
	(*) set -- "$*"    ;;
	esac
	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
	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
set -o braceexpand
bind '^H'=delete-word-backward
stty status '^T'

# history
FCEDIT="${VISUAL:-${EDITOR:-"vi"}}"
HISTFILE="$HOME/var/history/ksh.hist"
HISTSIZE=10000
HISTCONTROL="ignoredups:ignorespace"
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 -viR'
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 doas='doas '
alias fuck='doas '
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"}"}" --'
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)"
