# Source global definitions
if [ -f /etc/shrc ]; then
    . /etc/shrc
fi

# parse whatever follows in
# interactive mode only
case "$-" in
	*i*)
	#--- 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`
	# don't 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 ---	
   	# gmacs mode
    set -o gmacs
    # don't overwrite files with ?>"
    set -o noclobber
    # globstar mode 
    set -o globstar
    # !-style history
    set -o histexpand
    # mark directories 
    set -o markdirs
    # export variables
    set -o allexport
    # multiline input mode 
    set -o multiline
    # 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="~/.shrc" inside ~/.profile) 
	# host
	hup(){ (read pid; kill -HUP $pid) </var/run/$1.pid; }
	case "$-" in *i*)
	    if /bin/test -z "${HOST}"; then
	        HOST="$(hostname)"
	    fi
	;;
	esac  
	# shell
	SHELL=/bin/ksh93
	SHACCT=${HOME}/.shrecord
	SHLV=2
	# 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" 
	# path
	if [ `id -u` = 0 ]; then
		PATH=/usr/pkg/sbin:/usr/sbin:/sbin:$PATH
	 else
		PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/X11R7/bin:/usr/local/bin
        PATH=$PATH:/usr/pkg/bin:/usr/pkg/sbin/:/usr/linux/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"
	# 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"
	LC_ALL="en_US.UTF-8"
	CONFIG_CHARSET=UTF-8
	# user settings
	USER=$(id -un)
	GROUP=$(id -ng $USER)
	TZ="Europe/Rome"
	CDPATH=.:$HOME:/usr/pkg
	CDSTACK=32
	CURSES_NO_UTF8_ACS=1
	MAIL=/var/mail/${LOGNAME}
	MAILCHECK=1
	PAPERSIZE=A4
	BLOCKSIZE=1m 
	GREP_OPTIONS='-d skip'
	TAB=$(printf '\t')
	TERM=xterm-256color
	EDITOR=nvi
	VISUAL=${EDITOR}
	COLORTERM=${TERM}
	BROWSER=ssurf
	NNTPSERVER="news://news.eternal-september.org"
	SLRNPULL_ROOT=$HOME/News/Spool
	EDT_KEYPAD_SETUP=${HOME}/.edt/edt_keypad_sun.xml
    MPD_HOST="127.0.0.1"
	MPD_PORT="6600"
	MPC_FORMAT="%title% \n%artist% - %album%"
	
	# X
	WM=CTWM
	#XDG_CURRENT_DESKTOP=CTWM
	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
   	MC_XDG_OPEN=xdg-open
   	XCURSOR_SIZE=""
   	XCURSOR_THEME=""
   	SUDO_ASKPASS=/usr/X11R7/bin/ssh-askpass 

	# devel
	LD_LIBRARY_PATH=/lib:/usr/lib:/usr/X11R7/lib:/usr/pkg/lib
	CPATH=/usr/include:/usr/X11R7/include:/usr/pkg/include
	PKG_CONFIG_PATH=/usr/lib/pkgconfig:/usr/X11R7/lib/pkgconfig:/usr/pkg/lib/pkgconfig
	PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/pkg/share/pkgconfig:/usr/pkg/qt5/lib/pkgconfig
	PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/pkg/share/x11-links/lib/pkgconfig
	
	 # pkgsrc
    CVS_RSH=ssh
    MAKECONF=/usr/pkg/etc/mk.conf
    MK_CONF=/usr/pkg/etc/mk.conf
    PKGSRCDIR=/usr/pkgsrc
    #SIGN_PACKAGES=gpg
    GPG=/usr/bin/gpg2
    GPG_SIGN_AS=0x2F562C1B07DB5EF6
    GPG_TTY=$(tty)
	PKG_PATH="https://cdn.netbsd.org/pub/pkgsrc/packages/NetBSD/amd64/9.2/All"

	#--- shell functions ---
	
	# read config
	r() {
		exec $SHELL $HOME/.shrc
	}
	
	# verbose ls
	dir() {
		ls -l | awk '{ if ( substr($1,1,1)== "d") {print}}'
	}
	
	# make dir and go to it 
	md() {
		command mkdir -p $1 && cd $1
	}

   function _cd
    {
	# change directory
	dir=$1
	arg=$2
	if [ "$arg" ]
	then
	  \cd "$dir" "$arg"
	elif [ "$dir" ]
	then
	  \cd "$dir"
	else
	  \cd
	fi
	# set prompt
	typeset dir="${PWD:-$(command pwd -L)}"
	dir="${dir#$HOME/}"
	case $dir in
	    "$HOME")
		PS1=$(printf "\033[35m%s\033[00m \033[37m$\033[00m " "\~");;
	     /*)
		PS1=$(printf "\033[35m%s\033[00m \033[37m$\033[00m " "${PWD}");;
	    *)
		PS1=$(printf "\033[35m%s\033[00m \033[37m$\033[00m " "\~/$dir");;
	    esac
    }
    alias cd='_cd'
    eval _cd

    # save to dir stack
	pushd() {
	dirname=$1
	cd ${dirname:?"Missing directory name."}
	DIRSTACK="$PWD ${DIRSTACK:-$OLDPWD}"
	printf "$DIRSTACK"
	}

	# change wkrd to top of dir stack
	popd() {
	DIRSTACK=${DIRSTACK#* }
	cd ${DIRSTACK%% *}
	printf "$PWD"
	}
	
	# change dir interectively
	q ()
	{
		printf '%s' "$d" | sed -Ee "s/'/'\\\\''/g; 1s/^/'/;\$s/\$/'/"
	}

	# print directory tree
	tree() {
		exec find -- ${1:-.} | sed -Ee '2,$s:[^/]*/:   :g; s:   ([^ ]+)$:|_ \1:'
	}
	
	# remove duplicate lines in files
	dedup() {
		exec awk '
		{
			lines[NR] = $0
			if ($0 in array)
				delete lines[array[$0]]
			array[$0] = NR
		}
		END {
			for (i = 1; i <= NR; i++)
				if (i in lines)
					print lines[i]
		}' "$@"
	}
	
	q ()
	{
		printf '%s' "$d" | sed -Ee "s/'/'\\\\''/g; 1s/^/'/; \$s/\$/'/"
	}
	
	ch ()
	{
		local 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 num
	
		# do nothing if no number
		if [ "$num" = "" ]
		then	return 0
		fi
	
		# invalid number
		if [ "$num" -lt 1 -o "$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() { 
		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"
		 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 rm :{} \;
		find . -size 0 -exec rm {} \;
	}

	# send SIGKILL
	stop() { 
		kill -9 "${@:-%%}"; 
	}
	
	pid() {
		 ps -e | grep $@ | cut -d" " -f1;
	}	 
	
	# move to a dot file 	
	dot() { 
		for file in "$@"; 
		  do mv -iv "$file" ."$file"; 
	    done 
	}
	
	# backup files
	bck() { 
		for file in "$@"; 
		  do cp -iv "$file" "$file".bak; 
		done 
	}

        sslconnect()
        {
                openssl s_client -connect $1:$2 -crlf
        }
        
        ssh_copy_id()
        {
                [ -f ~/.ssh/id_ed25519.pub ] && PK=id_ed25519
                cat ~/.ssh/${PK}.pub |  \
                        ssh $1 "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
        }
        
        dos2unix()
        {
                mv -f $1 $1.dos
                tr -d '\r' < $1.dos > $1                
        }                                               
                             
        killhup()                                       
        {                                               
                kill -HUP `cat /var/run/${1}.pid`       
        }
        
        rmknownhost()
        {
                [ -z $1 ] && echo "usage: $0 /path/to/known_hosts:line" && return
                ${SED} -i ${1#*:}d ${1%:*}
        }
        
        sslexpire()
        {
                echo | openssl s_client -showcerts -connect ${1}:443 2>/dev/null | \
                        openssl x509 -noout -dates
        }
        
        killhup()
        {
                kill -HUP `cat /var/run/${1}.pid`
        }  

	pwrd()
	{
		 ( tail -f -n0 /var/log/messages & ) \
		  | sed -n -e 's/^.*adapter: //p'
	}
	# 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
	}
	
	# launch tmux
	tm() {
		if (( $# )); then
		  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)
	}
	
	
	#--- 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'
	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 dict="dict -d english"
    alias mirror='noglob wget --mirror --no-parent --recursive --timestamping  --continue --recursive'
    alias myip='dig +short myip.opendns.com @resolver1.opendns.com'
    alias mutt=neomutt
	alias mc='/usr/pkg/libexec/mc/mc-wrapper.sh'
	alias vi='/usr/pkg/bin/nvi'
	alias slrn="slrn -i ~/.slrnrc -f ~/.newsrc"
	alias stations='xmessage -file ~/.stations &'
	alias libressl="/usr/pkg/libressl/bin/openssl"
	alias yt2mp3='youtube-dl -x --audio-format mp3 --audio-quality 0 --prefer-ffmpeg -o "%(title)s.%(ext)s"'
	alias pip3up="pip3 list --format=columns | sed -e '1,2d' | cut -d' ' -f1 | xargs pip3 install -U"
	alias w3m="w3m -s -F -graph"
    alias edt='~/.edt/edt'
    set -o gmacs
    ;;
*)
;;
esac
