# $Id$
# $MirOS: src/bin/mksh/dot.mkshrc,v 1.121 2017/08/08 21:10:21 tg Exp $
#-
# Copyright (c) 2002, 2003, 2004, 2006, 2007, 2008, 2009, 2010,
#		2011, 2012, 2013, 2014, 2015, 2016, 2017
#	mirabilos <m@mirbsd.org>
#
# Provided that these terms and disclaimer and all copyright notices
# are retained or reproduced in an accompanying document, permission
# is granted to deal in this work without restriction, including un-
# limited rights to use, publicly perform, distribute, sell, modify,
# merge, give away, or sublicence.
#
# This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
# the utmost extent permitted by applicable law, neither express nor
# implied; without malicious intent or gross negligence. In no event
# may a licensor, author or contributor be held liable for indirect,
# direct, other damage, loss, or other issues arising in any way out
# of dealing in the work, even if advised of the possibility of such
# damage or existence of a defect, except proven that it results out
# of said person's immediate fault when using the work as intended.
#-
# ${ENV:-~/.mkshrc}: mksh initialisation file for interactive shells

# catch non-mksh, non-lksh, trying to run this file
case ${KSH_VERSION:-} in
*LEGACY\ KSH*|*MIRBSD\ KSH*) ;;
*) \return 0 ;;
esac

# give MidnightBSD's laffer1 a bit of csh feeling
function setenv {
	if (( $# )); then
		\\builtin eval '\\builtin export "$1"="${2:-}"'
	else
		\\builtin typeset -x
	fi
}

# pager (not control character safe)
smores() (
	\\builtin set +m
	\\builtin cat "$@" |&
	\\builtin trap "rv=\$?; \\\\builtin kill $! >/dev/null 2>&1; \\\\builtin exit \$rv" EXIT
	while IFS= \\builtin read -pr line; do
		llen=${%line}
		(( llen == -1 )) && llen=${#line}
		(( llen = llen ? (llen + COLUMNS - 1) / COLUMNS : 1 ))
		if (( (curlin += llen) >= LINES )); then
			\\builtin print -nr -- $'\e[7m--more--\e[0m'
			\\builtin read -u1 || \\builtin exit $?
			[[ $REPLY = [Qq]* ]] && \\builtin exit 0
			curlin=$llen
		fi
		\\builtin print -r -- "$line"
	done
)

# customise your favourite editor here; the first one found is used
for EDITOR in "${EDITOR:-}" jupp jstar mcedit ed vi; do
	EDITOR=$(\\builtin whence -p "$EDITOR") || EDITOR=
	[[ -n $EDITOR && -x $EDITOR ]] && break
	EDITOR=
done

\\builtin alias ls=ls l='ls -F' la='l -a' ll='l -l' lo='l -alo'
\: "${HOSTNAME:=$(\\builtin ulimit -c 0; \\builtin print -r -- $(hostname \
    2>/dev/null))}${EDITOR:=/bin/ed}${TERM:=vt100}${USER:=$(\\builtin ulimit \
    -c 0; id -un 2>/dev/null)}${USER:=?}"
[[ $HOSTNAME = ?(?(ip6-)localhost?(6)) ]] && HOSTNAME=nil; \\builtin unalias ls
\\builtin export EDITOR HOSTNAME TERM USER

# minimal support for lksh users
if [[ $KSH_VERSION = *LEGACY\ KSH* ]]; then
	PS1='$USER@${HOSTNAME%%.*}:$PWD>'
	\\builtin return 0
fi

# mksh-specific from here
\: "${MKSH:=$(\\builtin whence -p mksh)}${MKSH:=/bin/mksh}"
\\builtin export MKSH

# prompts
PS4='[$EPOCHREALTIME] '; PS1='#'; (( USER_ID )) && PS1='$'; PS1=$'\001\r''${|
	\\builtin typeset e=$?

	(( e )) && REPLY+="$e|"
	REPLY+=${USER}@${HOSTNAME%%.*}:

	\\builtin typeset d=${PWD:-?}/ p=~; [[ $p = ?(*/) ]] || d=${d/#$p\//\~/}
	d=${d%/}; \\builtin typeset m=${%d} n p=...; (( m > 0 )) || m=${#d}
	(( m > (n = (COLUMNS/3 < 7 ? 7 : COLUMNS/3)) )) && d=${d:(-n)} || p=
	REPLY+=$p$d

	\\builtin return $e
} '"$PS1 "

# utilities
\\builtin alias doch='sudo mksh -c "$(\\builtin fc -ln -1)"'
\\builtin command -v rot13 >/dev/null || \\builtin alias rot13='tr \
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ \
    nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM'
if \\builtin command -v hd >/dev/null; then
	\:
elif \\builtin command -v hexdump >/dev/null; then
	function hd {
		hexdump -e '"%08.8_ax  " 8/1 "%02X " " - " 8/1 "%02X "' \
		    -e '"  |" "%_p"' -e '"|\n"' "$@"
	}
else
	function hd {
		\\builtin cat "$@" | hd_mksh "$@"
	}
fi

# NUL-safe and EBCDIC-safe hexdump (from stdin)
function hd_mksh {
	\\builtin typeset -Uui16 -Z11 pos=0
	\\builtin typeset -Uui16 -Z5 hv=2147483647
	\\builtin typeset dasc dn line i
	\\builtin set +U

	while \\builtin read -arn 512 line; do
		\\builtin typeset -i1 'line[*]'
		i=0
		while (( i < ${#line[*]} )); do
			dn=
			(( (hv = line[i++]) != 0 )) && dn=${line[i-1]#1#}
			if (( (pos & 15) == 0 )); then
				(( pos )) && \
				    \\builtin print -r -- "$dasc|"
				\\builtin print -nr "${pos#16#}  "
				dasc=' |'
			fi
			\\builtin print -nr "${hv#16#} "
			if [[ $dn = [[:print:]] ]]; then
				dasc+=$dn
			else
				dasc+=.
			fi
			(( (pos++ & 15) == 7 )) && \
			    \\builtin print -nr -- '- '
		done
	done
	while (( pos & 15 )); do
		\\builtin print -nr '   '
		(( (pos++ & 15) == 7 )) && \
		    \\builtin print -nr -- '- '
	done
	(( hv == 2147483647 )) || \\builtin print -r -- "$dasc|"
}

# Berkeley C shell compatible dirs, popd, and pushd functions
# Z shell compatible chpwd() hook, used to update DIRSTACK[0]
DIRSTACKBASE=$(\\builtin realpath ~/. 2>/dev/null || \
    \\builtin print -nr -- "${HOME:-/}")
\\builtin set -A DIRSTACK
function chpwd {
	DIRSTACK[0]=$(\\builtin realpath . 2>/dev/null || \
	    \\builtin print -nr -- "$PWD")
	[[ $DIRSTACKBASE = ?(*/) ]] || \
	    DIRSTACK[0]=${DIRSTACK[0]/#$DIRSTACKBASE/\~}
	\:
}
\chpwd .
cd() {
	\\builtin cd "$@" || \\builtin return $?
	\chpwd "$@"
}
function cd_csh {
	\\builtin typeset d t=${1/#\~/$DIRSTACKBASE}

	if ! d=$(\\builtin cd "$t" 2>&1); then
		\\builtin print -ru2 "${1}: ${d##*cd: $t: }."
		\\builtin return 1
	fi
	\cd "$t"
}
function dirs {
	\\builtin typeset d dwidth
	\\builtin typeset -i fl=0 fv=0 fn=0 cpos=0

	while \\builtin getopts ":lvn" d; do
		case $d {
		(l)	fl=1 ;;
		(v)	fv=1 ;;
		(n)	fn=1 ;;
		(*)	\\builtin print -ru2 'Usage: dirs [-lvn].'
			\\builtin return 1 ;;
		}
	done
	\\builtin shift $((OPTIND - 1))
	if (( $# > 0 )); then
		\\builtin print -ru2 'Usage: dirs [-lvn].'
		\\builtin return 1
	fi
	if (( fv )); then
		fv=0
		while (( fv < ${#DIRSTACK[*]} )); do
			d=${DIRSTACK[fv]}
			(( fl )) && d=${d/#\~/$DIRSTACKBASE}
			\\builtin print -r -- "$fv	$d"
			(( ++fv ))
		done
	else
		fv=0
		while (( fv < ${#DIRSTACK[*]} )); do
			d=${DIRSTACK[fv]}
			(( fl )) && d=${d/#\~/$DIRSTACKBASE}
			(( dwidth = (${%d} > 0 ? ${%d} : ${#d}) ))
			if (( fn && (cpos += dwidth + 1) >= 79 && \
			    dwidth < 80 )); then
				\\builtin print
				(( cpos = dwidth + 1 ))
			fi
			\\builtin print -nr -- "$d "
			(( ++fv ))
		done
		\\builtin print
	fi
	\\builtin return 0
}
function popd {
	\\builtin typeset d fa
	\\builtin typeset -i n=1

	while \\builtin getopts ":0123456789lvn" d; do
		case $d {
		(l|v|n)	fa+=" -$d" ;;
		(+*)	n=2
			\\builtin break ;;
		(*)	\\builtin print -ru2 'Usage: popd [-lvn] [+<n>].'
			\\builtin return 1 ;;
		}
	done
	\\builtin shift $((OPTIND - n))
	n=0
	if (( $# > 1 )); then
		\\builtin print -ru2 popd: Too many arguments.
		\\builtin return 1
	elif [[ $1 = ++([0-9]) && $1 != +0 ]]; then
		if (( (n = ${1#+}) >= ${#DIRSTACK[*]} )); then
			\\builtin print -ru2 popd: Directory stack not that deep.
			\\builtin return 1
		fi
	elif [[ -n $1 ]]; then
		\\builtin print -ru2 popd: Bad directory.
		\\builtin return 1
	fi
	if (( ${#DIRSTACK[*]} < 2 )); then
		\\builtin print -ru2 popd: Directory stack empty.
		\\builtin return 1
	fi
	\\builtin unset DIRSTACK[n]
	\\builtin set -A DIRSTACK -- "${DIRSTACK[@]}"
	\cd_csh "${DIRSTACK[0]}" || \\builtin return 1
	\dirs $fa
}
function pushd {
	\\builtin typeset d fa
	\\builtin typeset -i n=1

	while \\builtin getopts ":0123456789lvn" d; do
		case $d {
		(l|v|n)	fa+=" -$d" ;;
		(+*)	n=2
			\\builtin break ;;
		(*)	\\builtin print -ru2 'Usage: pushd [-lvn] [<dir>|+<n>].'
			\\builtin return 1 ;;
		}
	done
	\\builtin shift $((OPTIND - n))
	if (( $# == 0 )); then
		if (( ${#DIRSTACK[*]} < 2 )); then
			\\builtin print -ru2 pushd: No other directory.
			\\builtin return 1
		fi
		d=${DIRSTACK[1]}
		DIRSTACK[1]=${DIRSTACK[0]}
		\cd_csh "$d" || \\builtin return 1
	elif (( $# > 1 )); then
		\\builtin print -ru2 pushd: Too many arguments.
		\\builtin return 1
	elif [[ $1 = ++([0-9]) && $1 != +0 ]]; then
		if (( (n = ${1#+}) >= ${#DIRSTACK[*]} )); then
			\\builtin print -ru2 pushd: Directory stack not that deep.
			\\builtin return 1
		fi
		while (( n-- )); do
			d=${DIRSTACK[0]}
			\\builtin unset DIRSTACK[0]
			\\builtin set -A DIRSTACK -- "${DIRSTACK[@]}" "$d"
		done
		\cd_csh "${DIRSTACK[0]}" || \\builtin return 1
	else
		\\builtin set -A DIRSTACK -- placeholder "${DIRSTACK[@]}"
		\cd_csh "$1" || \\builtin return 1
	fi
	\dirs $fa
}

# base64 encoder and decoder, RFC compliant, NUL safe, not EBCDIC safe
function Lb64decode {
	\\builtin set +U
	\\builtin typeset c s="$*" t
	[[ -n $s ]] || { s=$(\\builtin cat; \\builtin print x); s=${s%x}; }
	\\builtin typeset -i i=0 j=0 n=${#s} p=0 v x
	\\builtin typeset -i16 o

	while (( i < n )); do
		c=${s:(i++):1}
		case $c {
		(=)	\\builtin break ;;
		([A-Z])	(( v = 1#$c - 65 )) ;;
		([a-z])	(( v = 1#$c - 71 )) ;;
		([0-9])	(( v = 1#$c + 4 )) ;;
		(+)	v=62 ;;
		(/)	v=63 ;;
		(*)	\\builtin continue ;;
		}
		(( x = (x << 6) | v ))
		case $((p++)) {
		(0)	\\builtin continue ;;
		(1)	(( o = (x >> 4) & 255 )) ;;
		(2)	(( o = (x >> 2) & 255 )) ;;
		(3)	(( o = x & 255 ))
			p=0
			;;
		}
		t+=\\x${o#16#}
		(( ++j & 4095 )) && \\builtin continue
		\\builtin print -n $t
		t=
	done
	\\builtin print -n $t
}
function Lb64encode {
	\\builtin set +U
	\\builtin typeset c s t table
	\\builtin set -A table -- A B C D E F G H I J K L M N O P Q R S T U V W X Y Z \
	    a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 + /
	if (( $# )); then
		\\builtin read -raN-1 s <<<"$*"
		\\builtin unset s[${#s[*]}-1]
	else
		\\builtin read -raN-1 s
	fi
	\\builtin typeset -i i=0 n=${#s[*]} v

	while (( i < n )); do
		(( v = s[i++] << 16 ))
		(( v |= s[i++] << 8 ))
		(( v |= s[i++] ))
		t+=${table[v >> 18]}${table[v >> 12 & 63]}
		c=${table[v >> 6 & 63]}
		if (( i <= n )); then
			t+=$c${table[v & 63]}
		elif (( i == n + 1 )); then
			t+=$c=
		else
			t+===
		fi
		if (( ${#t} == 76 || i >= n )); then
			\\builtin print -r $t
			t=
		fi
	done
}

# Better Avalanche for the Jenkins Hash
\\builtin typeset -Z11 -Uui16 Lbafh_v
function Lbafh_init {
	Lbafh_v=0
}
function Lbafh_add {
	\\builtin set +U
	\\builtin typeset s
	if (( $# )); then
	                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              