# $Id: functions,v 1.12 2021/07/19 13:23:46 nanons Exp $
#
# Functions for sh(1) and ksh(1)
#
# Contents of this file should be copied to the shell startup file
# defined in the $ENV environment variable (see shell/dot.kshrc).

# Always use numeric UIDs/GIDs in tar(1) archives for better privacy
tar() {
	case "$1" in
	-*) command tar -N "$@" ;;
	*) command tar "N$@" ;;
	esac
}

# Generate a random sequence of printable ASCII characters using
# arc4random(3) for secure passwords
# See also dicepassc for strong memorable passwords:
#	# pkg_add dicepassc
pwdgen() {
	jot -rc -s "" "${@:-64}" 32 126
}

# Get dictionary definition of a word online
# Usage: dict <word> [database]  # Print definition of <word>
#        dict                    # Print list of databases
dict() {
	[ -n "$1" ] && set -- "define ${2:-*} \"$1\""
	printf '%s\r\n' "${1:-show db}" quit | nc dict.org 2628
}

# Terminate all active TCP connections
# Requires doas(1) configured, see etc/doas.conf
dropall() {
	netstat -nv -p tcp "$@" | while read proto x x local remote x; do
		[ "${proto%6}" = "tcp" ] || continue
		port=${local##*.} local=${local%."$port"}:$port
		port=${remote##*.} remote=${remote%."$port"}:$port
		doas tcpdrop "$local" "$remote"
	done
}

# Request a new identity from Tor (may be rate limited!)
# Requires appending "ControlSocket /var/tor/control" to /etc/tor/torrc
# Requires doas(1) configured, see etc/doas.conf
newnym() {
	printf '%s\r\n' AUTHENTICATE "${@:-SIGNAL NEWNYM}" QUIT |
	    doas -u _tor nc -U /var/tor/control
}
