#!/usr/local/bin/bash

function clt_version {
    local pkg=com.apple.pkg.CLTools_Executables
    pkgutil --pkg-info="$pkg" |
        tee >(grep -Fve 'install-time:') \
            >(awk '/install-time:/{print $2}' | xargs date -r | xargs -I@ printf 'install-time: %s\n' @) \
            >/dev/null
}

function pipe_stds {
    #(echo out >&1; echo err >&2) 2> >(sed 's/^.*/ERR: "&"/') 1> >(sed 's/^.*/OUT: "&"/')
    echo 'Run the following form, the order of redirects is important.'
    echo 'command_one 2> >(command_for_stderr) 1> >(command_for_stdout)'
}

function direct_math {
    \bc -l <<< "scale=4; $*"
}

function remac {
    sudo /System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport -z
    sudo ifconfig en0 ether "$(openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//')"
    sudo networksetup -detectnewhardware
    ifconfig en0 | grep ether
}

function forward {
    local local=$1
    local server
    local remote

    if [[ $2 =~ .*:[0-9]+ ]]
    then
        server=$(cut -f1 -d: <<< "$2")
        remote=$(cut -f2 -d: <<< "$2")
    else
        server=$2
        remote=$3
    fi
    \ssh -NL "$local:localhost:$remote" "$server"
}

function csudo {
    # `sudo -su _www` logs in as _www and runs the shell from your $SHELL var
    local login

    while getopts 'Aa:BbC:c:D:Eeg:Hh::iKklnPp:r:SsT:t:U:u:Vv' opt
    do
        # shellcheck disable=SC2220,SC2213
        case $opt in
            i) login=true ;;
        esac
        # inefficient loop and switch because we need OPTIND to be set to the first non-flag index
    done

    if [[ ${login:-false} == "true" || ${*: $OPTIND:1} == su ]]; then
        read -rp "Did you want sudo -s? [Yn] " yn
        case $yn in
            [Nn]* ) \sudo "$@";;
            * ) \sudo -s ;;
        esac
    elif [[ ${*: $OPTIND:1} == echo ]]; then
        echo "You probably want echo | sudo tee" >&2
        \sudo -v
        builtin echo "${@: (($OPTIND+1))}"
    else
        \sudo "$@"
    fi
}

function cscp {
    if xargs getopt '346BCpqrTvc:F:i:J:l:o:P:S:' -- <<< "$@" | { read -r c; [[ "${c}" =~ --\ .*:.*\ .*:.* ]]; }; then
        # 2 remotes, cannot use rsync, try: https://unix.stackexchange.com/questions/183504/how-to-rsync-files-between-two-remotes
        \scp -3 "$@"
        # https://stackoverflow.com/questions/32642188/rsync-equivalent-to-scp-3/32656801#32656801
        # ssh -M -R 9999:serverB:22 serverA rsync -a --rsh "ssh -p 9999" /path/to/source/files/ localhost:/path/to/destination/files/
        # where "9999" is any port number you like, as long as it matches in both places, and "22" is the SSH port number on serverB
    else
        # shellcheck disable=SC2034
        local RSYNC_RSH="/usr/bin/ssh -oRequestTTY=no -oRemoteCommand=none"
        until rsync -aLvz --append-verify --partial --progress --timeout=10 "$@"; do sleep 1; echo retrying; done
    fi
}

function cps {
    if [ $# == 1 ]; then
        pgrep -fil "$1"
    else
        ps "$@"
    fi
}

function cfind {
    if [ "$(uname)" = "Darwin" ]; then
        \find -x "$@"
    else
        #handle multiple search locations
        PLACE="$1"
        shift 1
        \find "$PLACE" -xdev "$@"
    fi
}

function cdiff {
    if hash git &>/dev/null; then
        git diff --no-index --color-words "$@"
    else
        \diff "$@"
    fi
}

function ramdrive {
    diskutil partitionDisk "$(hdiutil attach -nomount "ram://$(bc <<< '24 * 1024 ^ 3 / 512')")" 1 GPTFormat APFSX 'ramdisk' '100%'
}

function clocate {
    if [ "$(uname)" = "Darwin" ]; then
        mdfind "name:$*"
    else
        cdllocate "$*"
    fi
}

function csed {
    if [ "$(uname)" = "Darwin" ]; then
        sed -E "$@"
    else
        sed -r "$*"
    fi
}

function colors {
    if [ "${COLORTERM}" != truecolor ]; then
        for i in {0..31} ; do
            for j in {0..7} ; do
                printf "[7;(38;05;%d)mColor %-3d[0m\t" $((i + j * 32)) $((i + j * 32))
            done;
            echo ''
        done;
        echo -n "[0m"
    else
        local script='BEGIN{
    s = "/\\";
    total_cols = term_cols*term_lines;
    for (colnum = 0; colnum<total_cols; colnum++) {
        r = 255-(colnum*255/total_cols);
        g = (colnum*510/total_cols);
        b = (colnum*255/total_cols);
        if (g>255) g = 510-g;
        printf "\033[48;2;%d;%d;%dm", r,g,b;
        printf "\033[38;2;%d;%d;%dm", 255-r,255-g,255-b;
        printf "%s\033[0m", substr(s,colnum%2+1,1);
        if (colnum%term_cols == term_cols-1) printf "\n";
    }
    printf "\n";
    }'
        awk -v term_cols="${width:-$(tput cols || echo 80)}" \
            -v term_lines="${height:-$(tput lines || echo 1)}" \
            "$script"
    fi
}

function loveSongsForCamden {
    options_found=0
    while getopts ':vn:N:' OPT; do
        options_found=1
        # shellcheck disable=SC2214
        case $OPT in
            v|+v)
                mdfind kind:music album:camden | sort -nt / -k+11 | while read -r line; do printf "\n %s" "$line"; afplay "$line"; done &
                ;;
            n|+n)
                mdfind kind:music album:camden | sort -nt / -k+11 | grep -E --color='never' "/$OPTARG-.*$" | while read -r line; do afplay "$line"; done &
                ;;
            N|+N)
                shift $(( OPTIND - 1 ))
                OPTIND=1
                mdfind kind:music album:camden | sort -nt / -k+11 | grep -E --color='never' -i "[^/]*$*[^/]*/[^/]*$" | while read -r line; do afplay "$line"; done &
                ;;
            *)
                echo "usage: ${0##*/} [+-vn album-number] +-N album name" >&2
                return 2
        esac
    done
    if ((!options_found));then
        mdfind kind:music album:camden | sort -nt / -k+11 | while read -r line; do afplay "$line"; done &
    fi
}

function dedup_dirs {
    readarray -t new < <(printf "%s\n" "${DIRSTACK[@]:1}" | sort -u)
    dirs -c
    for dir in "${new[@]}"; do
        if [ "$dir" = "$PWD" ]; then continue; fi
        builtin pushd -n "$dir" >/dev/null
    done
}

function chdir {
    if [ $# -eq 2 ]; then
        # use -b to go up the stack
        if [ "$1" != '-b' ]; then
            # $1 is set back to it's own value, $2 is set to how many dirs to go up to
            # The number to go up to is calculated from left of path: ~/a = 1, ~/a/b = 2
            set -- "$1" "$(bc "($(tr -dc '/' <<< "${PWD//$HOME/\~}" | wc -c) + 1) - $2")"
        fi
        pushd "$(cut -d / -f "1-$2" <<< "${PWD//$HOME/\~}" | sed -e "s|\~|$HOME|")" || return
    elif [ -n "$1" ]; then
        pushd "${@//\~\?/$HOME/}" || return
    else
        pushd ~ || return
    fi
}

function pushd() {
    builtin pushd "$@" >/dev/null || return
    dedup_dirs
    dirs
}

function ccalendar {
    echo 'Today in history:'
    if [ "$TERM" != 'dumb' ]; then
        calendar 2>/dev/null | awk '{printf "%s %s",$1,$2; $1=$2=""; print "\t[0;38;5;122m"$0"[0m"}'
    else
        calendar 2>/dev/null | awk '{printf "%s %s",$1,$2; $1=$2=""; print "\t[0;36m"$0"[0m"}'
    fi
}

function getIp {
    if [ $# -gt 0 ]; then
        if [ "$1" = "-6" ]; then
            getIpv6
        elif [ "$1" = "-4" ]; then
            getIpv4
        else
            echo "Usage: getIp [-4] [-6]" >&2
        fi
    else
        getIpv4
    fi
}

function getIpv4 {
    getIpv 4
}

function getIpv6 {
    getIpv 6
}

function getIpv {
    # dig +short myip.opendns.com @resolver1.opendns.com
    \curl "-$1" -s http://icanhazip.com/s
}

function mailIpTo {
    getIp -4 | mail -s "$(whoami)'s IP update" -F camden.narzt@gmail.com
}

function zipup {
    zip -r "$1" "$1"
    mv "$1.zip" ../
}

function cnotify {
    osascript "$HOME/.bash.d/cnotify.scpt" "$@"
}

# shellcheck source=./fplay.sh
source "$HOME/.bash.d/fplay.sh"

function ccal {
    awk -v month="$(date +%m)" -v day="$(date +%e)" -f "$HOME/.bash.d/ccal.awk" - <(cal -y) <<EOF
10 31
4 25
2 14
2 2
EOF
}

function unix {
    date -r "$1"
}

function password {
    if [ -z "$*" ]; then
        echo "Must provide title for new password item" >&2
        echo "eg: $0 Best Buy" >&2
        return 1
    fi
    op item create login title="$*" --generate-password
}

function getPasswordFor {
    if [ $# -eq 0 ]; then
        echo "Missing item title" >&2
        return 1
    fi
    if ! op read --no-newline "op://${2:-Private}/$1/password"; then
    readarray -t id < <(op item list | awk "/$1/{print \$1}")
    if [ "${#id[@]}" -gt 1 ]; then
        echo "Too many matches for title" >&2
        return 1
    elif [ "${#id[@]}" -eq 0 ]; then
        echo "No matches for title" >&2
        return 1
    fi
    op read --no-newline "op://${2:-Private}/${id[*]}/password"
    fi
}

function getUsernameFor {
    if [ $# -eq 0 ]; then
        echo "Missing item title" >&2
        return 1
    fi
    op read --no-newline "op://${2:-Private}/${1:-}/username"
}

function ctar {
    local CREATE
    local FILE

    while getopts 'aBb:C:cf:HhI:JjkLlmnOoPpqrSs:T:tUuvW:wX:xyZz' opt
    do
        # shellcheck disable=SC2220,SC2213
        case $opt in
            c) CREATE=true ;;
            f) FILE=$OPTARG ;;
        esac
    done

    if ! [[ ${CREATE:-false} == "true" ]]; then
        tar "$@"
    else
        if ! [[ "${FILE:-x}" =~ .*\.t?gz ]]; then
            set -- "${*/.tar/.tgz}"
        fi
        tar "${@: 1:$((OPTIND -1))}" --use-compress-program pigz "${@: $OPTIND}"
    fi
}

function cpbcopy {
    if [ $# -ge 1 ]; then
        pbcopy < "$*"
    else
        pbcopy
    fi
}

function checkIsDistro {
    docker pull "$1:$2" &>/dev/null
}

function checkIsUbuntu {
    checkIsDistro ubuntu "$1"
}

function checkIsDebian {
    checkIsDistro debian "$1"
}

function checkIsRocky {
    checkIsDistro rockylinux/rockylinux "$1"
}

function checkIsFedora {
    checkIsDistro fedora "$1"
}

function checkIsRHEL {
    checkIsDistro "registry.redhat.io/${1/rhel/ubi}/ubi" || checkIsDistro "registry.access.redhat.com/${1/rhel/ubi}/ubi" latest || checkIsDistro "registry.access.redhat.com/$1/${1%%[0-9]*[0-9]}" latest
}

# shellcheck disable=SC2034
function makeRHELArgs {
    # shellcheck disable=SC2016
    local c1='subscription-manager register --username "$RHEL_USERNAME" --password "$RHEL_PASSWORD" --auto-attach'
    local c2='dnf install epel-release'
    local -n largs=$1
    largs=("$c1" '&&' "$c2")
}

function docker_internal_env {
    local IMAGE
    local args=()
    local envs=()
    if [[ "$1" == rocky:* ]] || [[ "$1" == rockylinux:* ]]; then
        IMAGE="rockylinux/rockylinux:${1#*:}"
    elif [[ "$1" == *:* ]]; then
        IMAGE="$1"
    elif checkIsUbuntu "$1"; then
        IMAGE="ubuntu:$1"
    elif checkIsDebian "$1"; then
        IMAGE="debian:$1"
    elif checkIsRocky "$1"; then
        IMAGE="rockylinux/rockylinux:$1"
    elif checkIsRocky "${1#el}"; then
        IMAGE="rockylinux/rockylinux:${1#el}"
    elif checkIsFedora "$1"; then
        IMAGE="fedora:$1"
    elif checkIsRHEL "$1"; then
        local version=${1##[a-z]*[a-z]}
        if [[ ${version:-8} -ge 8 ]]; then
            IMAGE="registry.redhat.io/ubi${version}/ubi"
            # OLD_REGISTRY="registry.access.redhat.com/ubi${version}/ubi"
        else
            IMAGE="registry.access.redhat.com/rhel${version}/rhel"
        fi

        makeRHELArgs args
        local RHEL_ID=ppwb5hgbzvd4lcvfeo5ga3jgoq
        if ! op whoami 2>/dev/null; then
            # shellcheck disable=SC1090
            source <(op signin)
        fi
        # shellcheck disable=SC2155
        export RHEL_USERNAME=$(getUsernameFor $RHEL_ID)
        # shellcheck disable=SC2155
        export RHEL_PASSWORD=$(getPasswordFor $RHEL_ID)
        envs=('-e' 'RHEL_USERNAME' '-e' 'RHEL_PASSWORD')
    else
        echo "Couldn't find proper distro for $1" >&2
        return 1
    fi

    # docker -H ssh://eve.local run ... <- note -H must be before run

    if [ "$(uname -m)" = 'x86_64' ]; then
        local arch=amd64
    else
        local arch=arm64
    fi

    envs+=('-e' "BASH_INIT_CMDS=${args[*]}")

    echo "arch=$arch"
    echo "envs=(${envs[*]})"
    echo "IMAGE=$IMAGE"
}
function enter {
    source <(docker_internal_env "$@")
    docker_run bash --login --init-file '<(echo "$BASH_INIT_CMDS")'
}
function run {
    source <(docker_internal_env "$@")
    shift
    docker_run bash -c "$*"
}
function docker_run {
    docker run --platform="linux/$arch" -it -v "$PWD:/mnt/pwd" "${envs[@]}" --security-opt seccomp=unconfined "$IMAGE" "$@"
}
function postgresql-upgrade-database {
    if [ $# -lt 2 ] || [ "$1" -eq "$2" ]; then
        echo "Usage: brew postgresql-upgrade-database 14 16" >&2
        return 255
    fi
    if [ "$1" -lt "$2" ]; then
        local V1=postgresql@$1
        local V2=postgresql@$2
    else
        local V1=postgresql@$2
        local V2=postgresql@$1
    fi
    "$(brew --prefix "$V2")/bin/pg_upgrade" -b "$(brew --prefix "$V1")/bin" -d "${HOMEBREW_PREFIX}/var/${V1}" -D "${HOMEBREW_PREFIX}/var/${V2}"
}

function vergte() {
    echo -e "$1\n$2" | sort -rCV
}
function verlte() {
    echo -e "$2\n$1" | sort -rCV
}
function vergt() {
    ! verlte "$@"
}
function verlt() {
    ! vergte "$@"
}

function xcode-clean() {
    PATH="$PATH:/Applications/Xcode.app/Contents/Developer/usr/bin"
    rm -rf ~/Library/Developer/Xcode/DerivedData
    rm -rf ~/Library/Developer/Xcode/Archives
    rm -rf ~/Library/Developer/Xcode/*\ DeviceSupport
    rm -rf ~/Library/Caches/com.apple.dt.Xcode
    xcrun simctl shutdown all && xcrun simctl erase all
}

function functions() {
    declare -F | \sed -Ee 's/declare -f ([^ ]+)/\1/' | grep -Eve '^(git_prompt|gp|shell_session)?_'
}

function aliases() {
    alias | \sed -Ee 's/alias ([^=]+)=.*/\1/'
}

function variables() {
    declare | rg '^[^ \t].*=.' | rg -vie '[ _]IFS' -e COMPREPLY | \sed -Ee 's/^([^=]+)=.*/\1/'
}

function start_under_debugger() {
    read -rp "Did you want to just use lldb? [Yn] " yn
    # shellcheck disable=SC2016
    case $yn in
        [Nn]* )
            echo 'nc -lU "lldb.sock"'
            echo "darwin-debug --unix-socket=lldb.sock -- \"$*\""
            echo 'lldb -p "$pid_from_nc"'
            ;;
        * ) lldb -- "$@";;
    esac
}

function service_to_interface {
    networksetup -listnetworkserviceorder | sed -n '/^([0-9]/ N; s/\n/ /g; p' | awk -v "name=$1" '$0 ~ name {sub(")","",$NF); print $NF}'
}

function ssid(){
    sudo ipconfig setverbose 1
    ipconfig getsummary $(service_to_interface Wi-Fi) | grep -Ee '\bSSID' | grep -v redacted | cut -d: -f 2 | tr -d '[:space:]'
    echo
    sudo ipconfig setverbose 0
}

function czip() {
    local file='-'
    local dir='./'
    read -ra args < <(getopt 'ctxf:C:' "$@")
    set -- "${args[@]}"
    while :; do
        case "$1" in
            -c)
                command=create
                shift
                ;;
            -t)
                command=list
                shift
                ;;
            -x)
                command=extract
                shift
                ;;
            -f)
                file="$2"
                shift 2;
                ;;
            -C)
                dir="$2"
                shift 2;
                ;;
            --)
                shift;
                break
                ;;
        esac
    done

    echo "d: $dir f: $file c: $command"

    case "$command" in
        create)
            printf -v files -- '-subdir %s ' "$@"
            # shellcheck disable=SC2086
            echo aa archive -output_file "${file%%.aar}.aar" $files -dir "$dir" ;;
        list) echo aa list -input_file "${file}" "$@" ;;
        extract) echo aa extract -input_file "${file}" -dir "$dir" ;;
    esac
}

function volume() {
    if [ $# -ne 1 ]; then
        echo "Valid arguments are: 0-100, mute, unmute" >&2
        exit 1
    fi

    local volume="$1"
    local -l muted
    muted=$(osascript -e 'get output muted of (get volume settings)')
    local -i oldVolume
    oldVolume=$(osascript -e 'get output volume of (get volume settings)')

    if [ "$volume" = "mute" ] && [ "$muted" == 'false' ]; then
        osascript -e "set volume output muted true"
    elif [ "$volume" = "mute" ]; then
        read -rp "Already muted, did you want to unmute? [yn] " yn
        case $yn in
            [Yy]* ) osascript -e "set volume output muted false";;
        esac
    elif [ "$volume" = "unmute" ]; then
        osascript -e "set volume output muted false"
    elif [ "$volume" -eq "$oldVolume" ]; then
        read -rp "Volume already set to $volume, did you want to unmute? [yn] " yn
        case $yn in
            [Yy]* ) osascript -e "set volume output muted false";;
        esac
    elif [ "$volume" -ge 0 ] && [ "$volume" -le 100 ]; then
        if [ "$muted" = 'true' ]; then  osascript -e "set volume output muted false"; fi
        osascript -e "set volume output volume $volume"
    else
        echo "Valid arguments are: 0-100, mute, unmute" >&2
        exit 1
    fi
}

function heic2jpeg(){
    sips -s format jpeg --out "${1%.*}.jpg" "$1"
}

function cls() {
    local -a flags
    local -a files
    local -a dirs
    local -a things
    shopt -u nocaseglob
    shopt -u nocasematch
    local DISABLE_HEADER=false
    while [[ "$#" -gt 0 ]]; do
        if [ "${1:1:1}" != "-" ]; then
            case "$1" in
                -*F*|-*w*|-*L*|-*s*|-*I*|-*t*)
                    flags+=("$1")
                    flags+=("$2")
                    shift 2
                    ;;
                -*1*)
                    DISABLE_HEADER=true
                    flags+=("$1")
                    shift
                    ;;
                -*d*)
                    DISABLE_HEADER=true
                    flags+=("$1")
                    shift
                    ;;
                -*)
                    flags+=("$1")
                    shift
                    ;;
                *)
                    things+=("$1")
                    shift
                    ;;
            esac
        else
            case "$1" in
                #--hyperlink|
                --classify|--absolute|--color|--colour|--icons|--width|--level|--sort|--ignore-glob|--time|--time-style)
                    flags+=("$1")
                    flags+=("$2")
                    shift 2
                    ;;
                --oneline|--treat-dirs-as-files)
                    DISABLE_HEADER=true
                    flags+=("$1")
                    shift
                    ;;
                -*)
                    flags+=("$1")
                    shift
                    ;;
                *)
                    things+=("$1")
                    shift
                    ;;
            esac
        fi
    done

    for thing in "${things[@]}"; do
        if [ -d "$thing" ]; then
            dirs+=("$thing")
        else
            files+=("$thing")
        fi
    done

    flags+=(--header --group --git)
    # flags+=('--hyperlink=auto')

    case "${#things[*]}" in
        0)
            if [[ "$PWD" != '/opt/homebrew'* ]] && [[ "$(readlink -f "$PWD")" != '/opt/homebrew'* ]]; then
                flags+=('--git-ignore')
            fi
            eza "${flags[@]}"
            ;;
        1)
            if [[ "${things[*]}" != '/opt/homebrew'* ]] && [[ "$(readlink -f "${things[*]}")" != '/opt/homebrew'* ]]; then
                flags+=('--git-ignore')
            fi
            eza "${flags[@]}" "${things[*]}"
            ;;
        *)
            if [ "${#files[*]}" -gt 0 ]; then
                eza "${flags[@]}" "${files[@]}"
                if [ "${#dirs[*]}" -gt 0 ]; then
                    echo
                fi
            fi
            for i in "${!dirs[@]}"; do
                if ! $DISABLE_HEADER; then
                    if [ "${i:-0}" -gt 0 ]; then
                        printf "\n%s:\n" "${dirs[i]}"
                    else
                        echo "${dirs[i]}:"
                    fi
                fi
                if [[ "${dirs[i]}" != '/opt/homebrew'* ]] && [[ "$(readlink -f "${dirs[i]}")" != '/opt/homebrew'* ]]; then
                    eza --git-ignore "${flags[@]}" "${dirs[i]}"
                else
                    eza "${flags[@]}" "${dirs[i]}"
                fi
            done
            ;;
    esac
    shopt -s nocaseglob
    shopt -s nocasematch
}

function _dump_defaults_clean(){
    local old
    old=$(shopt -p nullglob)
    shopt -s nullglob
    for f in .*.plist; do
        mv "$f" "${f#.}";
    done
    eval "$old"
    \find . -name '*.plist' -print0 | xargs -0 plutil -convert xml1 --
}

function _dump_defaults_internal() {
    mkdir -p "$HOME/Developer/Bash/dot-files/Library/Preferences${1-}"
    pushd "$HOME/Developer/Bash/dot-files/Library/Preferences${1-}" || return
    # shellcheck disable=SC2086
    defaults ${1-} domains | tr ' ,' '\n' | grep . | xargs -I@ defaults ${1-} export @ @.plist
    _dump_defaults_clean
    popd || return
}

function _dump_defaults_stubborn() {
    mkdir -p "$HOME/Developer/Bash/dot-files/Library/Preferences-stubborn"
    pushd "$HOME/Developer/Bash/dot-files/Library/Preferences-stubborn" || return
    find /System/Volumes/Data/Library/Preferences/ -name '*.plist' -execdir defaults export /System/Volumes/Data/Library/Preferences/{} "$HOME/Developer/Bash/dot-files/Library/Preferences-stubborn/{}" \;
    _dump_defaults_clean
    popd || return
}

function dump_defaults() {
    _dump_defaults_internal
    _dump_defaults_internal -currentHost
    _dump_defaults_stubborn
}

function apply_symbol() {
    if [ $# -ne 2 ]; then
        echo "apply_symbol symbol_name folder"
        return 1
    fi
    xattr -w 'com.apple.icon.folder#S' "$(printf '{"sym":"%s"}' "$1")" "$2"
}

function nato () {
    emacsclient --eval "(with-temp-buffer (insert (mapconcat 'identity server-eval-args-left (char-to-string ?\s))) (nato-region (point-min) (point-max)) (setq server-eval-args-left nil) (buffer-string))" -- "$@" | tr -d '"'
}

function lines () {
    sed -n -f <(printf '%sp\n' "$@")
}

function awakefor () {
    pgrep -x "$*" | xargs caffeinate -simw
}

function http() {
    # shellcheck disable=SC2016
    ruby -n -l -rnet/http/status -e 'puts Net::HTTP::STATUS_CODES[$_.to_i]' <<< "$@"
}

function catbin () {
    case $(type -t "$1") in
        alias)
            alias "$1";;
        keyword)
            help "$1";;
        function)
            command -V "$1";;
        builtin)
            help "$1";;
        file)
            local path
            path="$(which "$1")"
            if file -I "$path" | grep -q binary; then
                codesign -dv "$path"
            else
                bat "$path"
            fi
            ;;
        *)
            echo "$1 not found";;
    esac
}

function cul(){
    # underline text
    if [ $# -gt 0 ]; then
        ul <<< "${*//?/&_}"
    else
        sed 's/./&_/g' | ul
    fi
}

function catch() {
    # usage: `catch stdout_varname stderr_varname command arg1 arg2 ...`
    {
        IFS=$'\n' read -r -d '' "${1}";
        IFS=$'\n' read -r -d '' "${2}";
        (IFS=$'\n' read -r -d '' _ERRNO_; return "${_ERRNO_}");
    } < <((printf '\0%s\0%d\0' "$( ( ( ({ shift 2; "${@}"; echo "${?}" 1>&3-; } | tr -d '\0' 1>&4-) 4>&2- 2>&1- | tr -d '\0' 1>&4-) 3>&1- | exit "$(cat)") 4>&1-)" "${?}" 1>&2) 2>&1)
}

function free(){
    pages=$(vm_stat | grep -e "^Pages free" | awk '{print $NF}' | tr -d '.')
    bytes=$(\bc -l <<< "$pages * $(pagesize)")
    units -o "%0.f GB free" -t "$bytes bytes" gigabytes
}

function groupadd() {
    group_to_add_to="$1"
    shift
    if [ "${group_to_add_to-}" = "--help" ] || [ "${group_to_add_to-}" = "-h" ]; then
        echo "Usage: groupadd groupname user1 [user2, ...]" >&2
    fi
    for username_to_add in "$@"; do
        sudo dseditgroup -o edit -a $username_to_add -t user "$group_to_add_to"
    done
}

function enable_keyboard_nav(){
    defaults write NSGlobalDomain AppleKeyboardUIMode -int 3
}
