## Copyright © 2018, 2019, 2020, 2021, 2022, 2023, 2024 Oleg Pykhalov <go.wigust@gmail.com>
## Released under the GNU GPLv3 or any later version.

if [ -f "/etc/skel/.bashrc" ]
then
    # Load the skel profile's settings.
    source "/etc/skel/.bashrc"
fi

if [ -f "$HOME/.bash_vterm" ] && [[ $INSIDE_EMACS == vterm ]]
then
    source "$HOME/.bash_vterm"
fi

if [ -f "$HOME/.bash_aliases" ]
then
    # Load the Bash aliases and functions.
    source "$HOME/.bash_aliases"
fi

if [ -f "$HOME/.bash_guix" ]
then
    source "$HOME/.bash_guix"
fi

function dmesg()
{
    if [[ -z ${@:1} ]] && [[ -e "${HOME}/.guix-profile/bin/spacer" ]]
    then
        sudo /run/current-system/profile/bin/dmesg \
             --reltime \
             --human \
             --nopager \
             --decode \
             --ctime \
             --follow \
             --color=always \
            | "${HOME}/.guix-profile/bin/spacer"
    else
        sudo /run/current-system/profile/bin/dmesg
    fi
}

alias ,h="${BROWSER} ~/.guix-profile/share/doc/concise-gnu-bash/concise-gnu-bash.pdf"
alias ,c='command'

# Count number of code lines
alias ,l='tokei'

# Show Git repository statics
alias ,g='onefetch'

alias rm="rm -i"
alias cp="cp -i"
alias mv="mv -i"

alias mtr="sudo mtr --show-ips --aslookup"

alias xclipp='xclip -selection secondary'
alias svg=xdot

alias hosts='hosts --auto-sudo'
alias log='sudo lnav /var/log'

alias lsns='lsns --notruncate --output-all'
alias goaccess='goaccess --log-format=COMBINED'

alias catj=gron
alias sqlite-visualize=sqleton

alias tree="tree --dirsfirst -C"
alias free="free -mht"
alias psc='ps xawf -eo pid,user,cgroup,args'

alias markdown-github=grip

alias iostat='iostat -xm 2'

alias dhall-to-yaml='dhall-to-yaml --omit-empty'

alias noise-brown="mpv --no-resume-playback --loop '/srv/video/metube/Smoothed Brown Noise.webm'"

mem()
{
    cat <<EOF
The top 5 applications using most RAM:
$(ps -eo pid,%mem,cmd --sort=-%mem | head -n 6)
EOF
}

httping()
{
    case "$1" in
        majordomo*)
            command httping -s --colors https://www.majordomo.ru
            ;;
        *)
            command httping -s --colors "$@"
            ;;
    esac
}

emacs()
{
    case "$1" in
        signals)
            "$BROWSER" https://emacs.stackexchange.com/a/44087
            ;;
        tty)
            emacs -nw -Q "${@:2}"
            ;;
        *)
            command emacs "$@"
    esac
}

emc()
{
    # Setting TERM is required to fix colors in tmux running inside Alacritty.
    TERM=xterm-256color command emacsclient --create-frame --tty "$@"
}

guile()
{
    (
        if [ "$INSIDE_EMACS" == "vterm" ]
        then
            unset INSIDE_EMACS
        fi
        case "$1" in
            wisp)
                exec -a "$0" guile -x .w --language=wisp "${@:2}"
                ;;
            *)
                exec -a "$0" guile "$@"
                ;;
        esac
    )
}

cat()
{
    if [[ "${*:-1}" == /proc/*/environ ]]
    then
        command cat "${@: -1}" | tr '\000' '\n'
    elif [[ "${*:-1}" == *.md ]]
    then
        command glow "$@"
    else
        command cat "$@"
    fi
}

benchmark()
{
    hyperfine "$@"
}

lsd()
{
    if [ "$INSIDE_EMACS" == "vterm" ]
    then
        exa --all --long "$@"
    else
        ls "$@"
    fi
}

if [ -f "$HOME/.guix-profile/etc/profile.d/autojump.sh" ]
then
    source "$HOME/.guix-profile/etc/profile.d/autojump.sh"
fi

# http://puzan.info/linux/2014-05-14-direnv.html
if [ -f "$HOME/.guix-profile/bin/direnv" ]
then
    eval "$(direnv hook bash)"
fi

man_in_emacs()
{
    emacsclient --eval "(man \"$1\")"
}

man_to_pdf()
{
    man -t "$1" | ps2pdf - "$1.pdf"
}

stat_link()
{
    stat --format=%N "$@"
}

# Origin <https://www.fsf.org/blogs/directory/the-free-software-directory-needs-you-irc-meetups-every-friday-1>.
#
# Every Friday at 12:00-15:00 EDT (16:00 to 19:00 UTC)
# meet on IRC in the #fsf channel on irc.freenode.org
date_fsf()
{
    date --date='TZ="America/New_York" 12:00 this Fri'
}

cl()
{
    echo "$(tput cols)x$(tput lines)"
}

alias bedtime='sudo loginctl suspend'

alias aria2c='aria2c --seed-time=0'

ihs()
{
    GUILE_INSTALL_LOCALE=0                                      \
    GUIX_BUILD_OPTIONS=''                                       \
    IHS_USER=pyhalov                                            \
    IHS_PASS="$(pass show majordomo/private/hms/pyhalov)"       \
    CVM_USER=cron                                               \
    CVM_PASS="$(pass show majordomo/private/cvm/cron)"          \
    command ihs "$@"
}

if [[ -e "${HOME}/.bash.d/nix.bash" ]]
then
    source "${HOME}/.bash.d/nix.bash"
fi

rg()
{
    case "$1" in
        edit)
            last_command="$(history -w /dev/stdout | tail --lines=2 | head --lines=1)";
            if [[ "$last_command" =~ 'rg' ]] && [[ "$last_command" != *last_command* ]]
            then last_output="$(eval "$last_command")"
                 emacsclient --no-wait +"$(echo "$last_output" | cut -d: -f 2)" "$(echo "$last_output" | cut -d: -f 1)"
            else
                emacsclient --no-wait "$@"
            fi
            stumpish emacsclient
            ;;
        *)
            command rg "$@"
    esac
}

# TODO: readlink could fail to enter `guix environment`
# alias wi-pure-bash="env -i $(readlink $(which bash)) --noprofile --norc"

# TODO: Escape window names with asterisks.
# wi_x_resize_window ()
# {
#     window_name=$(xwininfo | grep 'Window id' | awk '{ print $5 }')
#     xdotool search --name "$window_name" windowsize $1 $2
# }

iptables()
{
    case "$1" in
        block)
            sudo --login command iptables -I INPUT -s "$2" -j DROP
            ;;
        --help)
            command iptables --help
            echo "\
Extra commands:
block  block IP-ADDRESS on INPUT chain"
            ;;
        *)
            command sudo iptables "$@"
            ;;
    esac
}

ansible_host()
{
    ansible --inventory "$1", "$1" --become --ask-become-pass "${@:2}"
}

yq()
{
    command yq --width "$(tput cols)" "$@"
}

jc()
{
    if [[ $# -eq 0 ]]
    then
        glow "https://github.com/kellyjonbrazil/jc"
    else
        command jc "$@"
    fi
}

jord_vm_ip()
{
    gms vm ip "$1" | recsel -pip_address | awk '{ print $2 }'
}

jord_ansible_service_start()
{
    vm="$(gms vm ip "$1" | recsel -pip_address | awk '{ print $2 }')"
    ansible --user sup --private-key="$HOME/.ssh/id_rsa_sup" --inventory "$vm", \
            "$vm" --module-name service --args "name=$2 state=started"          \
            --become --ask-become-pass

}

jord_web_loadavg()
{
    watch --color "seq -f 'web%gs' 15 37 | xargs guix environment -l $HOME/src/guile-loadavg/guix.scm -- $HOME/src/guile-loadavg/pre-inst-env loadavg weather"
}

parallel_curl()
{
    parallel --will-cite -k 'printf "domain: %s\n" {1}; curl --max-time 10 -L -s -o /dev/null -w "ip-address: %{remote_ip}\nstatus_code: %{http_code}" {1}; printf "\n\n"' ::: "$@"
}

jord_web_account_check()
{
    parallel --will-cite -k 'printf "domain: %s\n" {1}; curl --max-time 10 -L -s -o /dev/null -w "ip-address: %{remote_ip}\nstatus_code: %{http_code}" {1}; printf "\n\n"' \
        ::: "$(gms account website "$1" | recsel -pname | awk '{ print $2 }')"
}


guix_export_archive()
{
    path="$1"
    destination="$2"
    guix archive --export -r "$path" \
        | ssh "$destination" guix archive --import
}

ssh_keygen_rsa()
{
    file="$1"
    ssh-keygen -b 4096 -m pem -f "$HOME/.ssh/id_rsa_$file"
}

ssh_keygen_show_host_key()
{
    ssh-keygen -lf <(ssh-keyscan -p 1022 "$1" 2>/dev/null)
}

activity()
{
    ps -ef | awk '{ print $1 }' | sort | uniq | wc -l;
}

alias t5='TMOUT=5'
alias close='TMOUT=5'

# https://www.gnu.org/software/emacs/manual/html_node/efaq/Disabling-backups.html
alias ls='ls -B -p --color=auto'

if [ -f "$HOME/.nix-profile/share/bash-completion/completions/docker" ]
then
    source "$HOME/.nix-profile/share/bash-completion/completions/docker"
fi

if [ -f "$HOME/.bash_tmp" ]
then
    source "$HOME/.bash_tmp"
fi

alias bridge='bridge -color=always'
alias ip='ip -color=always'

jenkins_log()
{
    job="$1"
    curl --silent --user "admin:$(pass show magnolia/jenkins/admin)" \
         "https://jenkins.wugi.info/job/$job/lastBuild/consoleText"
}

jenkins_jobs_list()
{
    curl --silent --user "admin:$(pass show magnolia/jenkins/admin)" \
         https://jenkins.wugi.info/api/json/ \
        | jq -r '.jobs[] | [.name, .color] | @tsv'
}

jenkins_active_jobs()
{
    jenkins-jobs | grep --color=no red_anime
}

grub_list_entries()
{
    awk -F\" '$1=="menuentry " {print i++ " : " $2}' /boot/grub/grub.cfg
}

# https://github.com/jarun/Buku/wiki/Third-party-integration
fb()
{
    # save newline separated string into an array
    mapfile -t website <<< "$(buku -p -f 4 | column -ts$'\t' | fzf --multi)"

    # open each website
    for i in "${website[@]}"; do
        index="$(echo "$i" | awk '{print $1}')"
        buku -p "$index"
        buku -o "$index"
    done
}

guix()
{
    guix_modules="$HOME/.local/share/chezmoi/dotfiles/guixsd/modules"
    guix_extra_modules=(
        "${HOME}/src/cgit.duckdns.org/guix/guix-wigust/guix"
        "${HOME}/src/gitlab.com/nonguix/nonguix"
        "${HOME}/src/gitlab.com/wigust/prometheus-shepherd-exporter"
    )
    case "$1" in
        manifest)
            case "$2" in
                apply)
                    command guix package \
                            -L "$HOME/.local/share/chezmoi/dotfiles/guixsd/modules" \
                            --fallback \
                            --manifest="$HOME/.local/share/chezmoi/dotfiles/manifests/$HOSTNAME.scm" "${@:3}"
                    ;;
                build)
                    command guix environment \
                            -L "$HOME/.local/share/chezmoi/dotfiles/guixsd/modules" \
                            --fallback \
                            --manifest="$HOME/.local/share/chezmoi/dotfiles/manifests/$HOSTNAME.scm" "${@:3}" \
                            -- sh -c 'exit 0'
                    ;;
            esac
            ;;
        home)
            case "$2" in
                build)
                    (
                        cd "${HOME}/.local/share/chezmoi" || exit 1
                        command guix home build \
                                -L "$HOME/.local/share/chezmoi/dotfiles/guixsd/modules" \
                                --fallback \
                                "$HOME/.local/share/chezmoi/dotfiles/guixsd/home/${HOSTNAME}.scm" "${@:3}"
                    )
                    ;;
                switch)
                    (
                        cd "${HOME}/.local/share/chezmoi"
                        guix_command=()
                        if [[ "${PRE_INST_ENV:-FALSE}" == TRUE ]]
                        then
                            guix_command+=("${HOME}/src/git.savannah.gnu.org/git/guix/pre-inst-env")
                        else
                            guix_command+=("command")
                        fi
                        guix_command+=(
                            guix home reconfigure
                        )
                        for module in "${guix_extra_modules[@]}"
                        do
                            guix_command+=("--load-path=${module}")
                        done
                        guix_command+=(
                            --load-path="$guix_modules"
                            --fallback
                        )
                        if [[ -n $allow_downgrades ]]
                        then
                            guix_command+=("--allow-downgrades")
                        fi
                        if [[ -n $fallback ]]
                        then
                            guix_command+=("--fallback")
                        fi
                        guix_command+=(
                            "$HOME/.local/share/chezmoi/dotfiles/guixsd/home/${HOSTNAME}.scm"
                            "${@:3}"
                        )
                        "${guix_command[@]}"
                    )
                    ;;
            esac
            ;;
        maintainer)
            mapfile -t output < <(git log --grep="gnu: Add" --format=%s --author=go.wigust@gmail.com)
            for line in "${output[@]}"
            do
                package="${line/gnu: Add /}"
                package="${package::-1}"
                case "$package" in
                    *Revert*|*service*|premake4|perl-strictures-2|perl-role-tiny-2|emacs-cl-generic|emacs-seq|emacs-emms-player-simple-mpv|php-with-bcmath|shlomif-cmake-modules|go-github-com-muesli-reflow|go-github-com-emirpasic-gods-trees-binaryheap|nginx-socket-cloexec)
                        printf ""
                        ;;
                    *go-github-com*)
                        printf ""
                        ;;
                    *zabbix-agentd*)
                        printf "zabbix-agentd\nzabbix-server\n"
                        ;;
                    *)
                        echo "$package"
                        ;;
                esac
            done
            ;;
        menu)
            {
                exec 3>&1
                mapfile -t options < <(
                    dialog --separate-output --title "Guix" --checklist "Guix Options" 22 72 3 \
                           -- --no-offload "--no-offload" off \
                           --commit "--commit" off \
                           --allow-downgrades "--allow-downgrades" off \
                           --fallback "--fallback" off \
                           --disable-authentication "--disable-authentication" off \
                           2>&1 2>&1 1>&3
                )
                declare -p options
                for option in "${options[@]}"
                do
                    if [[ "$option" == "--commit" ]]
                    then
                        exec 3>&1
                        options=("${options[@]/--commit}")
                        commit=$(dialog --backtitle "Guix commit" --inputbox "Enter Guix's Git commit" 8 60 2>&1 1>&3)
                        exec 3>&-
                    fi
                    if [[ "$option" == "--allow-downgrades" ]]
                    then
                        options=("${options[@]/--allow-downgrades}")
                        allow_downgrades=true
                    fi
                    if [[ "$option" == "--fallback" ]]
                    then
                        options=("${options[@]/--fallback}")
                        fallback=true
                    fi
                    if [[ "$option" == "--disable-authentication" ]]
                    then
                        options=("${options[@]/--disable-authentication}")
                        disable_authentication=true
                    fi
                done
            }
            {
                exec 3>&1
                mapfile -t selection < <(
                    dialog --separate-output --title "Guix" --checklist "Guix Operations" 22 72 3 \
                           "pull channels" "Test build and update channel file" "${STATE:-off}" \
                           pull "Pull new changes" "${STATE:-on}" \
                           "system build" "Build system" "${STATE:-on}" \
                           "home build" "Build home" "${STATE:-on}" \
                           "home switch" "Reconfigure home" "${STATE:-on}" \
                           "manifest apply" "Apply package manifest" "${STATE:-on}" \
                           "system switch" "Reconfigure system" "${STATE:-on}" \
                           "distribute" "Pull on remote hosts" "${STATE:-off}" \
                           "system deploy" "Deploy to remote hosts" "${STATE:-off}" \
                           2>&1 2>&1 1>&3
                )
                declare -p selection
                exec 3>&-
            }
            clear
            (
                set -ex
                for operation in "${selection[@]}"
                do
                    eval "guix $operation $options"
                done
            )
            ;;
        pull)
            case "$2" in
                channels)
                    (
                        set -e
                        cd "${HOME}/.local/share/chezmoi" || exit 1
                        make dotfiles/channels-current.scm
                        if [[ $(git diff dotfiles/channels-current.scm) != "" ]]
                        then
                            if git commit -m "channels-current: Update." dotfiles/channels-current.scm
                            then
                                :
                            else
                                exit 1
                            fi
                        fi
                    )
                    ;;
                *)
                    guix_command=(
                        "command"
                        "guix" "pull"
                    )
                    if [[ -n $channels_file ]]
                    then
                        guix_command+=(
                            "--channels=${channels_file}"
                        )
                    else
                        guix_command+=(
                            "--channels=${HOME}/.local/share/chezmoi/dotfiles/channels-current.scm"
                        )
                    fi
                    if [[ -n $dry_run ]]
                    then
                        guix_command=(
                            echo
                            "${guix_command[@]}"
                        )
                    fi
                    if [[ -n $commit ]]
                    then
                        guix_command+=("--commit=$commit")
                    fi
                    if [[ -n $allow_downgrades ]]
                    then
                        guix_command+=("--allow-downgrades")
                    fi
                    if [[ -n $fallback ]]
                    then
                        guix_command+=("--fallback")
                    fi
                    if [[ -n $disable_authentication ]]
                    then
                        guix_command+=("--disable-authentication")
                    fi
                    (set -ex; "${guix_command[@]}" "${@:2}"; sudo --login "${guix_command[@]}" "${@:2}")
            esac
            ;;
        distribute)
            "$(guix build --file="$HOME/.local/share/chezmoi/dotfiles/ansible/guix.scm" "${@:2}")"
            ;;
        prebuild)
            guix_command=(
                echo
                sudo --login
                GUIX_PACKAGE_PATH="$guix_modules"
                "${HOME}/src/git.savannah.gnu.org/git/guix/pre-inst-env"
                guix
                system
                build
                --fallback
                --no-grafts
            )
            for module in "${guix_extra_modules[@]}"
            do
                guix_command+=("--load-path=${module}")
            done
            guix_command+=(
                "$HOME/.local/share/chezmoi/dotfiles/guixsd/guixsd.scm"
            )
            sudo --login "${guix_command[@]}" "${@:2}"
            ;;
        prereconfigure)
            guix_command=(
                "${HOME}/src/git.savannah.gnu.org/git/guix/pre-inst-env"
                "guix"
            )
            for module in "${guix_extra_modules[@]}"
            do
                guix_command+=("--load-path=${module}")
            done
            guix_command+=(
                system reconfigure
                --load-path="$guix_modules"
                --fallback "$HOME/.local/share/chezmoi/dotfiles/guixsd/guixsd.scm"
                --no-grafts
                "$HOME/.local/share/chezmoi/dotfiles/guixsd/guixsd.scm"
            )
            sudo --login "${guix_command[@]}" "${@:2}"
            ;;
        # repl)
        #     GUILE_AUTO_COMPILE=0 command guix repl -L "$guix_modules" "${@:3}"
        #     ;;
        remote)
            case "$2" in
                reboot)
                    ansible-playbook <(
                        cat <<'EOF'
- hosts: guix_vm
  become: true
  tasks:
  - reboot: search_paths=/home/oleg/bin
EOF
                    )
                    ;;
            esac
            ;;
        substituters)
            cat <<'EOF'
The Guix project runs two official build farms that continuously build binary
substitutes, so users don't have to build everything at home. When installing
Guix or Guix System for the first time, you'll be asked whether to trust their
signatures and download their substitutes by default:

    https://ci.guix.gnu.org (Germany)
    https://bordeaux.guix.gnu.org (France)

For Guix users outside of Europe, connections to both of these can sometimes
be slow or censored.  Don't fret just yet: volunteers maintain unofficial
mirrors of the official servers that may be closer by:

    People's Republic of China
        https://mirrors.sjtug.sjtu.edu.cn/guix (mirrors ci.guix.gnu.org)
    Singapore
        https://bordeaux-singapore-mirror.cbaines.net
    United States of America
        https://bordeaux-us-east-mirror.cbaines.net (mirrors bordeaux.guix.gnu.org)
    Germany
        https://hydra-guix-129.guix.gnu.org (official mirror of bordeaux.guix.gnu.org in Berlin)
EOF
            ;;
        system)
            case "$2" in
                build)
                    sudo --login GUILE_LOAD_PATH="${HOME}/.local/share/chezmoi/dotfiles/guixsd/modules:${GUILE_LOAD_PATH}" command guix system build \
                         -L "$guix_modules" \
                         "${@:3}" \
                         "$HOME/.local/share/chezmoi/dotfiles/guixsd/$HOSTNAME.scm"
                    ;;
                deploy)
                    (
                        set -ex
                        guix deploy -L "$guix_modules" "${@:3}" \
                             "$HOME/.local/share/chezmoi/dotfiles/guixsd/deploy.scm"
                    )
                    ;;
                reconfigure)
                    sudo --login GUILE_LOAD_PATH="${HOME}/.local/share/chezmoi/dotfiles/guixsd/modules:${GUILE_LOAD_PATH}" command guix system reconfigure \
                         -L "$guix_modules" \
                         --no-bootloader "${@:3}" \
                         "$HOME/.local/share/chezmoi/dotfiles/guixsd/$HOSTNAME.scm"
                    ;;
                switch)
                    guix_command=(
                        sudo --login GUILE_LOAD_PATH="${HOME}/.local/share/chezmoi/dotfiles/guixsd/modules:${GUILE_LOAD_PATH}" command guix system reconfigure \
                             -L "$guix_modules" \
                             "${@:3}" \
                             "$HOME/.local/share/chezmoi/dotfiles/guixsd/$HOSTNAME.scm"
                    )
                    if [[ -n $allow_downgrades ]]
                    then
                        guix_command+=("--allow-downgrades")
                    fi
                    "${guix_command[@]}"
                    if [[ -n $fallback ]]
                    then
                        guix_command+=("--fallback")
                    fi
                    ;;
                *)
                    command guix system "${@:2}"
                    ;;
            esac
            ;;
        update)
            (
                set -e
                guix pull
                guix system build
                guix manifest
                guix system switch
                set +e
            )
            ;;
        master-staging)
            git -C "${HOME}/src/git.savannah.gnu.org/git/guix" shortlog -n upstream/master..upstream/staging
            ;;
        qemu)
            # https://wiki.archlinux.org/index.php/QEMU#Creating_bridge_manually
            printf -v macaddr "52:54:%02x:%02x:%02x:%02x" \
            $(( RANDOM & 0xff)) $(( RANDOM & 0xff )) $(( RANDOM & 0xff)) $(( RANDOM & 0xff ))

            sudo command qemu-system-x86_64 -daemonize -enable-kvm                      \
                 -smp cores=4,threads=1 -cpu host -m 4096 -vga virtio -full-screen      \
                 -net nic,model=virtio,macaddr="$macaddr" -net bridge,br=br0            \
                 "$@"
            ;;
        clean)
            (
                set -x
                command guix package --delete-generations=1m
                command guix pull --delete-generations=1m
                command guix gc --list-failures | xargs guix gc --clear-failures
                sudo --login command guix system delete-generations 1m
                sudo --login command guix pull --delete-generations=1m
                command guix home delete-generations 1m
            )
            ;;
        profiles)
            echo "$(readlink --canonicalize $HOME/.guix-profile)" \
                 "$(readlink --canonicalize /run/current-system)" \
                 "$(readlink --canonicalize $HOME/.config/guix/current)"
            ;;
        test-vm)
            eval "$(sed 's,-nic user[^ ]* ,,' "$(./pre-inst-env guix system vm --no-offload "$2")" | tail -1 | sed 's/\sexec\s//') -m 4096  -smp 2 -nic user,model=virtio-net-pci,hostfwd=tcp::10022-:22"
            ;;
        updatedb)
            updatedb \
                --localpaths=/gnu/store \
                --findoptions='( -path /gnu/store/.links -o -name *.drv -o -name *.chroot ) -prune -o -type f -print' \
                --output="$HOME/.config/guix/dbfile"
            ;;
        locate)
            locate -d "$HOME/.config/guix/dbfile" "${@:2}"
            ;;
        xpanes)
            guix_machines=(
                vm1.wugi.info
                vm2.wugi.info
                vm3.wugi.info
                vm4.wugi.info
                vm5.wugi.info
                ws1.wugi.info
                localhost
            )
            xpanes -c 'ssh {}' "${guix_machines[@]}"
            ;;
        depends)
            for package in $(guix package --list-installed | cut --fields=1)
            do
                if guix graph "$package" | grep --quiet "$2"
                then
                    echo "$package"
                fi
            done
            ;;
        *)
            command guix "$@"
            ;;
    esac
}

maintenance()
{
    case "$1" in
        upgrade)
            (
                set -xe
                cd "${HOME}/.local/share/chezmoi" || exit 1
                make dotfiles/nix/flake.lock
                if make dotfiles/nix/flake.nix
                then
                    :
                else
                    git restore dotfiles/nix/flake.lock
                fi
            )
            ;;
        *)
            command nix "$@"
            ;;
    esac
}

listen_ports()
{
    ss -tulpn | awk '{ print $5 }' | cut -d: -f 2 | sort -un | xargs echo
}

alias vnc-server-android="vncserver -AcceptSetDesktopSize=no -geometry 1280x720"

# jenkins_log()
# {
#     for project in $(curl -s -k "https://admin:$(pass show majordomo/public/jenkins.intr/admin)@jenkins.intr/api/json?pretty=true" | jq -r '.jobs[] | .name'); do
#         for job in $(curl -s -k "https://admin:$(pass show majordomo/public/jenkins.intr/admin)@jenkins.intr/job/$project/api/json" | jq -r '.jobs[] | .url'); do
#             echo "@ $job" |
#             curl -u "admin:$(pass show majordomo/public/jenkins.intr/admin)" -s -k "$job/job/master/lastBuild/consoleText"
#         done
#     done
# }

# https://markhneedham.com/blog/2015/11/14/jq-filtering-missing-keys/

alias get-todos='scp work:/home/user/src/jord/doc/todo.org ~/src/todo.org '

# nix-shell -E 'with import <nixpkgs> {}; callPackage ./default.nix {}' -A luaCrypto
# nix-build -E 'with import <nixpkgs> {}; callPackage ./default.nix {}';

# grep '^FAIL ' /tmp/6.txt | cut -d '/' -f 2- | cut -d ']' -f 1 | sed 's@^@ext/@'

nix_untar_docker()
{
    # argument example: /nix/store/vqi100nf7x7z82pr4lkagasmzl9zj0zp-docker-image-apache2-php56.tar.gz
    tar xv --wildcards '*/layer.tar' -f "$1" \
        | tee /tmp/tempstore \
        | xargs -n1 -I{} tar xvf {}
}

tmux_renumber_windows()
{
    tmux movew -r
}

nix_user_uid()
{
    nix-build -E 'with import <nixpkgs> {}; runCommand "foo" {} "id"'
}

nix_info()
{
    nix-shell -p nix-info --run "nix-info -m"
}

guix_packages_json()
{
    curl https://guix.gnu.org/packages.json
}

git_guix_pre_new_build()
{
    number="$1"
    git log --oneline \
        | head -n "$number" \
        | grep Add  \
        | awk '{ print $NF }' \
        | cut -d'.' -f 1 \
        | xargs ./pre-inst-env guix build --no-grafts
}

git_guix_pre_new_lint()
{
    number="$1"
    git log --oneline \
        | head -n "$number" \
        | grep Add  \
        | awk '{ print $NF }' \
        | cut -d'.' -f 1 \
        | xargs ./pre-inst-env guix lint
}

git_guix_pre_update()
{
    number="$1"
    git log --oneline \
        | head -n "$number" \
        | grep Update \
        | awk '{ print $3 }' \
        | cut -d: -f 1 \
        | xargs ./pre-inst-env guix build --no-grafts
}

git_guix_home()
{
    number="$1"
    git show "$number" | grep home | cut -d'"' -f 2
}

# archive_dir()
# {
#     for dir in $@; do
#         mv -vi "$dir" "$HOME/archive/src/"
#     done
# }

terraform_init_with_nix()
{
    terraform init -plugin-dir ~/.nix-profile/bin "$@"
}

terraform_init()
{
    terraform_init_with_nix -plugin-dir ~/go/src/gitlab.intr/majordomo/terraform-provider-majordomo
}

alias tsw='tmuxifier s web'
alias nn='notmuch new'
alias wtr='curl -H "Accept-Language: ru" wttr.in/Санкт-Петербург'
alias hylang='docker run --rm -it hylang'

nix_build()
{
    nix_build="$(which nix-build)"
    if [[ "$(readlink -f "$PWD")" =~ "majordomo" ]]
    then
        cmd="sshpass -Ppassphrase -p$(pass show majordomo/private/gitlab.intr/ssh/id_rsa_gitlab_intr) $nix_build --no-out-link"
        if grep --quiet buildLayeredImage default.nix
        then
            cmd="docker load --input $($cmd)"
        fi
    else
        cmd="$nix_build --no-out-link"
    fi
    case "$1" in
        20.03)
            $cmd "$HOME/src/nixpkgs-master" "${@:2}"
            ;;
        19.09)
            $cmd "$HOME/src/nixpkgs-master" "${@:2}"
            ;;
        master)
            $cmd "$HOME/src/nixpkgs-master" "${@:2}"
            ;;
        unstable)
            $cmd "$HOME/.nix-defexpr/channels/nixos-unstable" "${@:2}"
            ;;
        *)
            $cmd '<nixpkgs>' "$@"
    esac
}


nix_shell_python()
{
    PYTHONPATH="" nix-shell -p "python35.withPackages(ps: with ps; [ $* ])"
}

nixos_interactive_test()
{
    version="$1"
    nix-build build.nix \
              --cores 4 \
              -A "nixpkgsUnstable.php$version-test.driver" \
              --no-out-link --show-trace/bin/nixos-run-vms
}

terraform_refresh()
{
    NIX_SSL_CERT_FILE="$HOME/.guix-profile/etc/ssl/certs/Majordomo_LLC_Root_CA.crt" \
                     SSL_CERT_DIR="$HOME/.guix-profile/etc/ssl/certs" \
                     SSL_CERT_FILE="$HOME/.guix-profile/etc/ssl/certs/ca-certificates.crt" \
            terraform refresh
}

terraform_plan()
{
    NIX_SSL_CERT_FILE="$HOME/src/gitlab.intr/office/ssl-certificates/Majordomo_LLC_Root_CA.crt" \
                     SSL_CERT_DIR="$HOME/.guix-profile/etc/ssl/certs" \
                     SSL_CERT_FILE="$HOME/.guix-profile/etc/ssl/certs/ca-certificates.crt" \
            terraform plan -out=plan "$@"
}

terraform_import()
{
    NIX_SSL_CERT_FILE="$HOME/.guix-profile/etc/ssl/certs/Majordomo_LLC_Root_CA.crt" \
                     SSL_CERT_DIR="$HOME/.guix-profile/etc/ssl/certs" \
                     SSL_CERT_FILE="$HOME/.guix-profile/etc/ssl/certs/ca-certificates.crt" \
            terraform import "$@"
}

terraform_apply()
{
    NIX_SSL_CERT_FILE="$HOME/src/gitlab.intr/office/ssl-certificates/Majordomo_LLC_Root_CA.crt" \
                     SSL_CERT_DIR="$HOME/.guix-profile/etc/ssl/certs" \
                     SSL_CERT_FILE="$HOME/.guix-profile/etc/ssl/certs/ca-certificates.crt" \
                     terraform apply "plan"
}

terraform_apply_no_plan()
{
    NIX_SSL_CERT_FILE="$HOME/.guix-profile/etc/ssl/certs/Majordomo_LLC_Root_CA.crt" \
                     SSL_CERT_DIR="$HOME/.guix-profile/etc/ssl/certs" \
                     SSL_CERT_FILE="$HOME/.guix-profile/etc/ssl/certs/ca-certificates.crt" \
            terraform apply
}

terraform_apply_gitlab()
{
    grep resource gitlab/*.tf \
        | awk '{ gsub("\"",""); print $2, $3 }' \
        | sed 's/\s/./' \
        | sed 's/^/-target=/' \
        | xargs env NIX_SSL_CERT_FILE="/run/current-system/profile/etc/ssl/certs/Majordomo_LLC_Root_CA.crt" SSL_CERT_DIR="/run/current-system/profile/etc/ssl/certs" SSL_CERT_FILE="/run/current-system/profile/etc/ssl/certs/ca-certificates.crt" terraform apply plan
}

terraform_plan_gitlab()
{
    grep resource gitlab/*.tf \
        | awk '{ gsub("\"",""); print $2, $3 }' \
        | sed 's/\s/./' \
        | sed 's/^/-target=/' \
        | xargs env NIX_SSL_CERT_FILE="/run/current-system/profile/etc/ssl/certs/Majordomo_LLC_Root_CA.crt" SSL_CERT_DIR="/run/current-system/profile/etc/ssl/certs" SSL_CERT_FILE="/run/current-system/profile/etc/ssl/certs/ca-certificates.crt" terraform plan -out=plan
}

terraformer_import_github()
{
    terraformer import majordomo \
                --token "$GITHUB_TOKEN" \
                --organizations wugi-emacs \
                --resources=repositories
}

spb_log()
{
    ssh spb -- bzcat "$1"
}

ssh_guix_build_log_file()
{
    host="$1"
    file="$2"
    ssh "$host" -- guix build --log-file "$file" | xargs ssh "$host" -- bzcat
}

herd_reload()
{
    herd reload root "$HOME/.config/shepherd/init.scm"
}

herd_kill_services_via_awk()
{
    for service in $(awk '/define.*service/ { print $NF }' "$HOME/.config/shepherd/init.scm" | sed 's/-service//'); do
        pkill "$service"
    done
}

docker_strace()
{
    container="$1"
    docker top "$container" | tail -n +2 | awk '{ print $2 }' | sed 's/^/-p/' | xargs sudo strace -o "$HOME/$container.strace" -f -s 4096
}

docker_strace_pids()
{
    container="$1"
    docker top "$container" | tail -n +2 | awk '{ print $2 }' | sed 's/^/-p/';
}

vnc_server_zero()
{
    sudo chmod 666 /var/run/slim-vt7.auth
    xauth merge /var/run/slim-vt7.auth
    while true; do
        guix shell tigervnc-server -- x0vncserver -PasswordFile "$HOME/.vnc/passwd" -display :0 -rfbport 5960
        sleep 5
    done
}

ansible_cmdb_my()
{
    # https://itnext.io/create-a-host-inventory-in-a-minute-with-ansible-c7bf251166d9
    ansible -m setup --tree out/ all
    ansible-cmdb -t html_fancy_split -p local_js=1 out/
}

ansible_playbook_wrapper()
{
    host="$1"
    ANSIBLE_HOST_KEY_CHECKING="False" ansible-playbook                  \
            --private-key="$HOME/.ssh/id_rsa"                           \
            --user=root                                                 \
            --inventory="$host",                                        \
            --extra-vars=host="$host"                                   \
            --extra-vars=ansible_python_interpreter=/usr/bin/python3    \
            "${@:2}"
}

bash_history_top()
{
    # https://www.commandlinefu.com/commands/view/604/list-of-commands-you-use-most-often
    history | awk '{a[$2]++}END{for(i in a){print a[i] " " i}}' | sort -rn | head
}

fast_scan()
{
    parallel -j200% -n1 -a textfile-with-hosts.txt nc -vz {} ::: 22
}

alias guix-docker-image-minimal='guix pack -f docker --symlink=/bin=bin bash'
alias find-yml="find -maxdepth 2 -name '*.yml' | grep -vF '.travis.yml' | grep -vF '.gitlab'"
alias docker-describe-image='dive'
alias inxi='inxi --full'
alias ansible-playbook-ping-all="ansible-playbook <(echo -e '---\n- hosts: all\n  tasks:\n    - ping:')"
alias ansible-playbook-cache-all="ansible-playbook <(echo -e '---\n- hosts:\n  - all\n  gather_facts: True\n')"
alias clock='while sleep 1;do tput sc;tput cup 0 $(($(tput cols)-29));date;tput rc;done &'
alias type-like-movie='echo "You can simulate on-screen typing just like in the movies" | pv -qL 10'
alias top-by-memory='ps aux | sort -nk +4 | tail'
alias smtpd='python -m smtpd -n -c DebuggingServer localhost:1025'
alias biggest='du -s * | sort -n | tail'
alias colors='for code in {0..255}; do echo -e "\\e[38;05;${code}m $code: Test"; done'
alias ps-tree='ps awwfux | less -S'
alias share='script -qf | tee >(nc -kl 5000) >(nc -kl 5001) >(nc -kl 5002)'
alias internet-programs='lsof -P -i -n | cut -f 1 -d " "| uniq | tail -n +2'

md()
{
    mkdir -p "$@" && cd "$@"
}

kernel_graph()
{
    lsmod \
        | perl -e 'print "digraph \"lsmod\" {";<>;while(<>){@_=split/\s+/; print "\"$_[0]\" -> \"$_\"\n" for split/,/,$_[3]}print "}"' \
        | dot -Tpng \
        | feh -
}

netstat_graph()
{
    netstat -an \
        | grep ESTABLISHED \
        | awk '{print $5}' \
        | awk -F: '{print $1}' \
        | sort \
        | uniq -c \
        | awk '{ printf("%s\t%s\t",$2,$1) ; for (i = 0; i < $1; i++) {printf("*")}; print "" }' \
        | sort -k2 -n
}

random_password()
{
    length="$1"
    strings /dev/urandom | grep -o '[[:alnum:]]' | head -n "$length" | tr -d '\n'
}

# watch -n 1 mysqladmin --user=<user> --password=<password> processlist

alias alexa-top="curl -qsSl http://s3.amazonaws.com/alexa-static/top-1m.csv.zip 2>/dev/null | zcat | grep .de | head -1000 | awk -F, '{print }'"

dnsperf_my()
{
    # https://muff.kiev.ua/content/dnsperf-testirovanie-proizvoditelnosti-dns-servera
    sudo dnsperf -d ~/Downloads/dnsperf-example.txt -s 127.0.0.1 -l 60
}


tmuxifier_webs_user()
{
    account="$(ihs web unix "$1")"
    TMUXIFIER_USER="$(echo "$account" | recsel -P name)" \
        TMUXIFIER_HOST="$(echo "$account" | recsel -P server_name)"s \
        tmuxifier s ssh
}

tmuxifier_connect_host()
{
    host="$1"
    TMUXIFIER_USER=root TMUXIFIER_HOST="$host" tmuxifier w ssh-sudo
}

git_clean_up()
{
    for dir in apache2-php52 apache2-php53 apache2-php54 apache2-php55 apache2-php56 apache2-php70 apache2-php71 apache2-php72 apache2-php73 ; do
        cd $dir
        for branch in $(git branch -r | grep -v master | sed 's|origin/||'); do
            git push origin --delete "$branch"
        done
        cd -
    done
}

tmux_ls()
{
    command tmux ls | cut -d ':' -f 1 2>/dev/null
}

tmux()
{
    case "$1" in
        list)
            session="$(tmux-ls | fzf)"
            if [ "$session" == "" ]
            then
                return 1
            else
                command tmux at -t "$session"
            fi
            ;;
        *)
            command tmux "$@"
            ;;
    esac
}

docker_xorg()
{
    xhost +local:

    # MAYBE:
    # --device /dev/video0 \

    docker run -it \
            -v /tmp/.X11-unix:/tmp/.X11-unix \
            -e DISPLAY \
            --device /dev/dri \
            --device /dev/snd \
            -v /etc/localtime:/etc/localtime:ro \
            --device /dev/input \
            "$@"
}

obs_docker_setup()
{
    # https://github.com/mviereck/x11docker/wiki/Container-sound:-ALSA-or-Pulseaudio

    "$(guix build pulseaudio)/bin/pactl" load-module module-native-protocol-unix socket=/tmp/pulseaudio.socket
    cat > /tmp/pulseaudio.client.conf << EOF
default-server = unix:/tmp/pulseaudio.socket
# Prevent a server running in the container

autospawn = no
daemon-binary = /bin/true
# Prevent the use of shared memory

enable-shm = false
EOF
}

obs_docker()
{
    docker-xorg \
        --name obs \
        --rm \
        --env PULSE_SERVER=unix:/tmp/pulseaudio.socket \
        --env PULSE_COOKIE=/tmp/pulseaudio.cookie \
        --volume /tmp/pulseaudio.socket:/tmp/pulseaudio.socket \
        --volume /tmp/pulseaudio.client.conf:/etc/pulse/client.conf \
        --volume /home/oleg/obs:/home/obs \
        --volume /home/oleg/.Xauthority:/home/oleg/.Xauthority \
        --volume /srv/music/mp3:/home/obs/music \
        obs
}

pacmd()
{
    case "$1" in
        ladspa)
            command pacmd load-module module-ladspa-sink sink_name=compressor-stereo plugin=sc4_1882 label=sc4 control=1,1.5,401,-30,20,5,12
            ;;
        *)
            command pacmd "$@"
            ;;
    esac
}

projectile_ls()
{
    bash -c 'echo ${0:1:-1}' \
         "$(printf "%b" "$(emacsclient -e "(mapconcat 'identity (mapcar #'expand-file-name (projectile-load-known-projects)) \"\n\")")")" \
        | tr ' ' '\n'
}

projectile_command()
{
    "$@" "$(projectile-ls | fzf)"
}

alias projectile-cd="projectile-command cd"

alias projectile-magit="projectile-command magit"

microseconds_to_seconds()
{
    seconds="$1"
    microseconds=$(echo "scale=2;${seconds}/1000000" | bc)
    echo "$microseconds"
}

test_openvpn()
{
    server="$1"
    # https://serverfault.com/questions/262474/how-to-check-that-an-openvpn-server-is-listening-on-a-remote-port-without-using
    echo -e "\x38\x01\x00\x00\x00\x00\x00\x00\x00" |
        timeout 10 nc -u "$server" 1194 | cat -v
    # Output example: @$M-^HM--LdM-t|M-^X^@^@^@^@^@@$M-^HM--LdM-t|M-^X^@^@^@^@^@@$M-^HM--LdM-t|M-^X...
}

# jq like for http
alias hq='pup'

guix_graph_chromium()
{
    package="$1"
    GUILE_LOAD_PATH=/home/oleg/src/git.savannah.gnu.org/git/guix:GUILE_LOAD_PATH guix graph -b d3js \
"$package" > /tmp/out.html && chromium --app=file:///tmp/out.html
}

docker_run_ansible()
{
    docker run \
            --network=host \
            -v /home/oleg/src/dotfiles:/root/src/dotfiles \
            -v /root/.ssh:/root/.ssh \
            -v /home/oleg/.ansible-hosts:/etc/ansible/hosts \
            -v /home/oleg/telnet.yml:/telnet.yml \
            -v /home/oleg/ansible-out/ansible.cfg:/etc/ansible/ansible.cfg \
            --rm -it quay.io/ansible/molecule:2.22 sh
}


alias bash-pure='env -i "$(command -v bash)" --login --noprofile --norc'

alias root-shedule="sudo herd schedule mcron 10"
alias tmux-reload="tmux source-file ~/.tmux.conf"

less_color()
{
    LESSOPEN="| ~/.guix-profile/bin/src-hilite-lesspipe.sh %s"
    export LESSOPEN

    LESS=' -R '
    export LESS
}

container()
{
    case "$1" in
        lint)
            docker run --rm --interactive hadolint/hadolint:v1.17.2-8-g65736cb-debian < Dockerfile
            ;;
        ip)
            docker ps --format='{{.ID}}' \
                | xargs docker inspect \
                | jq -r '.[] | [.NetworkSettings.Networks.bridge.IPAddress, .Config.Image] | @tsv'
            ;;
        intr-list)
            mjru-docker-list-intr
            ;;
        intr-pull)
            group="$1" # For example: “mail”.
            for repo in $docker_list_intr; do
                docker pull "docker-registry.intr/$repo"
            done
            ;;
        intr-ps)
            ANSIBLE_NOCOLOR=1 ansible swarm -m shell -a 'docker ps --no-trunc' --become --ask-become-pass
            ;;
        *)
            docker "$@"
            ;;
    esac
}
if [ -f /run/current-system/profile/etc/bash_completion.d/docker ]; then
    source /run/current-system/profile/etc/bash_completion.d/docker
    complete -F _docker container
fi

ip_to_decimal()
{
    ip="$1" # e.g. 127.0.0.1
    perl -le "print unpack(\"N\", $ip)"
}

alias random-pass="perl -le 'print map { (a..z)[rand 26] } 1..8'"

urlescape ()
{
    perl -MURI::Escape -lne 'print uri_escape($_)' <<< "$1"
}

urlunescape ()
{
    perl -MURI::Escape -lne 'print uri_unescape($_)' <<< "$1"
}

build_farm()
{
    emacsclient -e "(wi-build-farm \"$1\")"
}

find_touch_go()
{
    find . -name '*.go' -exec touch {} +
}

function password()
{
    if [ "$#" -ne 2 ]
    then
        (
            cd "$HOME/.password-store" || exit
            pass show "$(find . -not -path './.gitattributes' -not -path './.git/*' -type f | sed 's@\./@@' | sed 's@\.gpg@@' | fzf)" \
                | xclip -i -sel p -f | xclip -i -sel c
        )
    else
        pass "$@"
    fi
}
if [ -f "$HOME/.guix-profile/etc/bash_completion.d/pass" ]; then
    source "$HOME/.guix-profile/etc/bash_completion.d/pass"
    complete -o filenames -F _pass password
fi
alias password='EDITOR=nano password'

genpass()
{
    tr -dc 'a-zA-Z0-9_#@.-' < /dev/urandom | head -c "${1:-14}"
}

pass_list_all()
{
    (
        cd ~/.password-store || exit
        for password in $(find . -not -path './.gitattributes' -not -path './.git/*' -type f | sed 's@\./@@' | sed 's@\.gpg@@'); do
            pass show "$password" | tr -d '\n'
            echo
        done
    )
}

gmail_mail()
{
    # Source: https://www.commandlinefu.com/commands/view/3380/check-your-unread-gmail-from-the-command-line
    curl -u "go.wigust:$(pass show myaccount.google.com/apppasswords/go.wigust)" \
            --silent "https://mail.google.com/mail/feed/atom" \
        | tr -d '\n' \
        | awk -F '<entry>' '{for (i=2; i<=NF; i++) {print $i}}' \
        | sed -n "s/<title>\(.*\)<\/title.*name>\(.*\)<\/name>.*/\2 - \1/p"

    # Alternative variant:
    # Checks your unread Gmail from the command line
    # curl -u username --silent "https://mail.google.com/mail/feed/atom" | perl -ne 'print "\t" if /<name>/; print "$2\n" if /<(title|name)>(.*)<\/\1>/;

}

gmail_send()
{
    rcpt="$1"

    # Send email with curl and gmail
    curl -n --ssl-reqd --mail-from "<go.wigust@gmail.com>" --mail-rcpt "$rcpt" --url smtps://smtp.gmail.com:465 -T file.txt
}

cmdfu()
{
    curl -L "http://www.commandlinefu.com/commands/matching/$*/$(echo -n "$@" | openssl base64)/plaintext";
}

clfavs()
{
    #  backup all your commandlinefu.com favourites to a plaintext file 

    URL="http://www.commandlinefu.com"
    wget -O - --save-cookies c --post-data "username=$1&password=$2&submit=Let+me+in" $URL/users/signin
    for i in $(seq 0 25 "$3"); do
        wget -O - --load-cookies c "$URL/commands/favourites/plaintext/$i" >> "$4"
    done
    rm -f c
}

gnuplot_bash_history()
{
    HISTTIMEFORMAT='' history \
        | awk '{a[$2]++}END{for(i in a){print a[i] " " i}}' \
        | sort -rn \
        | head > /tmp/cmds ; gnuplot -persist <<<'plot "/tmp/cmds" using 1:xticlabels(2) with boxes'
}

kill_xterm_on_display()
{
    display="$1"
    for pid in $(pidof xterm); do
        if [[ $1 = $(tr '\000' '\n' < "/proc/$pid/environ" | grep "$display" | cut -d= -f 2) ]]; then
            kill "$pid"
        fi
    done
}

docker_top_strace()
{
    container="$1"
    docker top "$container" \
        | awk '{ print $2 }' \
        | tail -n +2 \
        | sed 's/^/-p/' \
        | xargs strace -s 10000 -f -o /tmp/docker.strace
}

active_hms()
{
    curl -s --user jenkins:"$(pass show majordomo/private/jenkins/jenkins)" nginx{1,2}-mr:8080/hms | jq -r .active | uniq
}

jenkins_build_project_branch()
{
    dir="$1"
    project="$2"
    branch="$3"
    url="$JENKINS_URL/job/$dir/job/$project/job/$branch"

    curl -X POST                                        \
         -u "admin:$(pass show jenkins/admin-api-key)"  \
         "$url/build"

    echo "$url/lastBuild/console"
}

# Create a new directory and enter it
mkd()
{
	mkdir -p "$@"
	cd "$@" || exit
}

# Make a temporary directory and enter it
tmpd()
{
	local dir
	if [ $# -eq 0 ]; then
		dir=$(mktemp -d)
	else
		dir=$(mktemp -d -t "${1}.XXXXXXXXXX")
	fi
	cd "$dir" || exit
}

# Run `dig` and display the most useful info
digga()
{
	dig +nocmd "$1" any +multiline +noall +answer
}

alias feh-bg="feh --borderless --image-bg black --auto-zoom --draw-filename"

lsp_mode()
{
    docker run --tty --interactive --rm                                                 \
            --volume "$PWD:/mnt/workspace"                                              \
            --volume /etc/localtime:/etc/localtime:ro                                   \
            --volume "$HOME/.gnupg:${HOME}/.gnupg"                                      \
            --volume /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket    \
            --volume /tmp/.X11-unix:/tmp/.X11-unix                                      \
            --volume /etc/machine-id:/etc/machine-id:ro                                 \
            --volume /home/oleg/src/gitlab.intr/hms:/src                                      \
            --volume "$PWD/emacs.d/:/home/lsp/.emacs.d"                                 \
            --user 1000:1000                                                            \
            --env DISPLAY="$DISPLAY"                                                    \
            --network=host                                                              \
            "${1:-yyoncho/lsp-emacs-docker}" emacs
}

git_all_history()
{
    git log --oneline | awk '{ print $1 }' | xargs git show
}

git_grep_removed()
{
    git log --full-diff  -G '\*\*REMOVED\*\*'
}

git_prune()
{
    git reflog expire --expire=now --all && git gc --prune=now --aggressive
}

bfg()
{
    case "$1" in
        pass)
            command bfg --replace-text <(git-pass-secrets)
            ;;
    esac
}

atoi()
{
    #Returns the integer representation of an IP arg, passed in ascii dotted-decimal notation (x.x.x.x)
    IP=$1; IPNUM=0
    for (( i=0 ; i<4 ; ++i )); do
        ((IPNUM+=${IP%%.*}*$((256**$((3-i))))))
        IP=${IP#*.}
    done
    echo $IPNUM
}

itoa()
{
    #returns the dotted-decimal ascii form of an IP arg passed in integer format
    echo -n $(($(($(($((${1}/256))/256))/256))%256)).
    echo -n $(($(($((${1}/256))/256))%256)).
    echo -n $(($((${1}/256))%256)).
    echo $((${1}%256))
}

pactl_ladspa()
{
    # TODO: LADSPA_PATH=/gnu/store/…-swh-plugins/lib/ladspa
    # https://github.com/gotbletu/shownotes/blob/master/pulseaudio-dynamic-range-compression.md
    pactl load-module module-ladspa-sink master=0 sink_name=compressor-stereo plugin=sc4_1882 label=sc4 control=1,1.5,401,-30,20,5,12
    pactl load-module module-ladspa-sink master=1 sink_name=compressor-stereo plugin=sc4_1882 label=sc4 control=1,1.5,401,-30,20,5,12
}

docker_openresty()
{
    docker run                                  \
            --entrypoint ''                     \
            --interactive                       \
            --name openresty                    \
            --network=host                      \
            --tty                               \
            openresty/openresty:bionic bash
}

nix_python_with_pkgs()
{
    nix-shell -p python "python.withPackages (python-packages: with python-packages; [ $* ])"
}

bpython()
{
    nix-shell -p python3 "python3.withPackages (python-packages: with python-packages; [ bpython ])" --run bpython
}

http_prompt()
{
    nix-shell -I "$HOME/.nix-defexpr/channels/nixos-unstable"   \
              -p http-prompt                                    \
              --run "http-prompt $@"
}

nix_python2_with_pkgs()
{
    nix-shell -p python2 "python2.withPackages (python-packages: with python-packages; [ $* ])"
}


firefox()
{
    case "$1" in
        kill)
            pgrep -fa firefox-wrapped | grep -v 'test' | cut -d ' ' -f 1 | xargs kill
            ;;
        sync)
            rsync --archive --progress "$HOME/.mozilla/firefox/j56dvo43.default-1520714705340" vm1.wugi.info:.mozilla/firefox/
            ;;
        *)
            command firefox "$@"
    esac
}

firefox_esr_debian()
{
    xhost +local:

    docker run                                  \
      --tty                                     \
      --interactive                             \
      --rm                                      \
      --name                                    \
      firefox-java                              \
      --env                                     \
      DISPLAY="$DISPLAY"                        \
      --volume                                  \
      /tmp/.X11-unix:/tmp/.X11-unix             \
      cmaohuang/firefox-java                    \
      /usr/bin/firefox                          \
      --new-instance
}

mitmproxy()
{
    PYTHONPATH='' command mitmproxy --set ssl_insecure=true "$@"
}

alias ssh-clean='find ~/.ssh -type s -delete'

alias pass='EDITOR=nano pass'
alias ansible-vault='EDITOR=nano ansible-vault'

alias sw1-dh507='connect sw1-dh507'
alias sw1-mr11="connect sw1-mr11"

alias nix='EDITOR=less VISUAL="emacsclient -cn" nix'

alias dotfiles='EDITOR=nano dotfiles'
if [ -f "$HOME/.nix-profile/share/bash-completion/completions/chezmoi.bash" ]; then
    source "$HOME/.nix-profile/share/bash-completion/completions/chezmoi.bash"
    complete -o default -F __start_chezmoi dotfiles
fi

if [ -f "$HOME/.guix-profile/etc/bash_completion.d/restic" ]; then
    source "$HOME/.guix-profile/etc/bash_completion.d/restic"
    complete -o default -F __start_restic backup
fi

mycut()
{
    command cut --characters="-$(tput cols)" "$@"
}

src_clean()
{
    for directory in src archive/src; do
        command src-clean --directory=$directory --author=go.wigust@gmail.com --ignore=src/dotfiles,src/rofi-themes,src/rfc,src/guix-videos,src/guile,src/fdroiddata,src/emacs-tramp-auto-auth,src/docker-nextcloud,archive/src/sendnotify,archive/src/php,archive/src/my-guix,archive/src/malware-scanner,archive/src/linux-panic,archive/src/linux,archive/src/guile-shepherd,archive/src/groovy,archive/src/gentoo,archive/src/freebsd,archive/src/cpython,archive/src/bash,archive/src/arch-packages,archive/src/arch-community
    done
}

transmission_remote()
{
    case "$1" in
        clean)
            command transmission-remote --list | awk '$2 == "100%" { system("transmission-remote --torrent " $1 " --remove") }'
            ;;
        *)
            command transmission-remote "$@"
            ;;
    esac
}

rg()
{
    case "$1" in
        dist)
            command rg "${@:2}" "$HOME"/{src/nixpkgs-master,src/guix,archive/src/{gentoo,freebsd,openbsd-ports,arch-{community,packages}}}
            ;;
        *)
            command rg --no-heading "$@"
            ;;
    esac
}

if [ -f "$HOME/.bash.d/slack.bash" ]
then
    # shellcheck source=.bash.d/mjru.bash
    source "$HOME/.bash.d/slack.bash"
fi

if [ -f "$HOME/.bash.d/mjru.bash" ]
then
    # shellcheck source=.bash.d/mjru.bash
    source "$HOME/.bash.d/mjru.bash"
fi

chezmoi()
{
    case "$1" in
        add-all)
            for file in $(command chezmoi diff | awk '/a\/home/ { print $NF }' | sed 's/^a//'); do
                command chezmoi add "$file"
            done
            ;;
        *)
            command chezmoi "$@"
            ;;
    esac

}

if [ -f "$HOME/.bash_completion.d/mail" ]
then
    source "$HOME/.bash_completion.d/mail"
fi

if [ -f "$HOME/.bash_completion.d/connect" ]
then
    source "$HOME/.bash_completion.d/connect"
fi

gitlab()
{
    GITLAB_API_PRIVATE_TOKEN="$(pass show majordomo/private/gitlab.intr/tokens/terraform)"
    GITLAB_API_ENDPOINT="https://gitlab.intr/api/v4"
    GITLAB_API_HTTPARTY_OPTIONS="{verify: false}"

    case "$1" in
        create_project)
            group="$2"
            name="$3"
            command gitlab create_project "$name" "{visibility: public, namespace_id: $group}"
            echo "https://gitlab.intr/$group/$name"
            echo "git@gitlab.wugi.info:$group/$name.git"
            ;;
        *)
            command gitlab "$@"
    esac
}

youtube_dl_to_org()
{
    jq --join-output '.entries[] | "- [ ] [[https://www.youtube.com/watch?v=", .id, "]", "[", .title, "]]\n"' "$@"
}

gita()
{
    case "$1" in
        emacs)
            emacsclient -cn "$(command gita ls "$2")"
            ;;
        cd)
            cd "$(command gita ls "$2")"
            ;;
        --help)
            command gita --help "$@"
            glow https://github.com/nosarthur/gita
            ;;
        week)
            PAGER='' command gita super log --format="%ai %H %s" --date=relative --since="${2:-1} weeks ago" "${@:3}"
            ;;
        *)
            command gita "$@"
            ;;
    esac
}

alias godaddy="GODADDY_DOMAIN_NAME=wugi.info godaddy"
wugi.info()
{
    case "$1" in
        a)
            godaddy list a
            ;;
        cname)
            godaddy list cname
            ;;
        ns)
            godaddy list ns
            ;;
    esac
}

stumpwm_refcard()
{
    (
        cd "/home/oleg/src/git.savannah.gnu.org/git/guix-maintenance/doc/refcard" || exit 1
        # convert -density 200 -rotate 90 "$(guix build -f build.scm)"/stumpwm-refcard.pdf - | zathura -
        case "$1" in
            wallpaper)
                convert -trim -quality 100 -negate -density 130 -rotate 90 "$(guix build -f build.scm)"/stumpwm-refcard.pdf /tmp/out.png; feh --bg-center /tmp/out.png
                ;;
            *)
                zathura "$(guix build -f build.scm)"/stumpwm-refcard.pdf
        esac
    )
}

ci()
{
    "$BROWSER" "$CI"
}

elktail()
{
    case "$1" in
        --help|-h)
            command elktail --help
            echo "\

  general commands
    nginx         show nginx logs
    hms           show log messages from hms index
    trace         trace OPERATION_IDENTITY in hms index
"
            ;;
        nginx)
            command elktail -url 'http://es:9200' -i 'nginx-*' -n 10000 -l -f '%remote_addr %hostname %path %method %code %http_host'
            ;;
        hms)
            # log_level:DEBUG
            # log_level:ERROR
            # stack:"$(curl --silent --user "jenkins:$(pass show majordomo/private/jenkins/jenkins)" -X GET http://nginx1.intr:8080/hms | jq --raw-output .active)"
            command elktail \
                    -url 'http://es:9200' \
                    -i 'hms-*' \
                    -n 10000 \
                    -l \
                    -f '%@timestamp %log_level %stack %sleuth_trace %log_message' \
                    -a "$(printf "%s" "$(date --utc '+%FT%H:%M:00.000Z' --date '4 hours ago')")" \
                    "${@:3}" \
                | grep --invert-match "ftp-user not found by" \
                | grep --invert-match "org.apache.catalina.connector.RequestFacade" \
                | grep --invert-match "Running the evict task with compensationTime" \
                | grep --invert-match "Resolving eureka endpoints via configuration" \
                | grep --invert-match "quotaUsed: " \
                | grep --invert-match "unixAccounts quotaReport for host"
            ;;
        trace)
            (
                set -x
                command elktail \
                        -url 'http://es:9200' \
                        -i 'hms-*' \
                        -n 10000 \
                        -l \
                        -f '%@timestamp %log_level %stack %sleuth_trace %log_message' \
                        -a "$(printf "%s" "$(date --utc '+%FT%H:%M:00.000Z' --date '5 hours ago')")" \
                        sleuth_trace:"$2"
            )
            ;;
        *)
            command elktail "$@"
            ;;
    esac
}

brute()
{
    sudo grep 'Connection closed' /var/log/messages \
        | grep --perl-regexp '(?:[0-9]{1,3}\.){3}[0-9]{1,3}' --only-matching \
        | grep --invert-match 127.0.0.1 \
        | uniq \
        | fzf \
        | xargs sudo ipset add brute
}

docker()
{
    case "$1" in
        deploy)
            command docker rm -f novnc
            command docker rm -f monitoror
            monitoror run
            vnc client novnc
            ;;
        *)
            command docker "$@"
    esac
}

lsgpu()
{
    printf "Memory: %s\n" "$(glxinfo | grep -i -o 'device|memory\|[0-9]\{1,12\} MB' | head -n 1)"
}

efi()
{
    if [ -d /sys/firmware/efi ]
    then
        echo UEFI
    else
        echo BIOS
    fi
}

mediatomb()
{
    case "$1" in
        start)
            command mediatomb -e enp34s0 -f Videos/.mediatomb "${@:2}"
            ;;
        *)
            command mediatomb "$@"
    esac
}

if [ -z $IN_NIX_SHELL ]
then
    if [ -e $HOME/.guix-profile/lib/bash/libguile-bash.so ]
    then
        enable -f "$HOME"/.guix-profile/lib/bash/libguile-bash.so scm
        if [ -e "$HOME"/.bash.d/bash.scm ]
        then
            GUILE_AUTO_COMPILE=0 scm "$HOME"/.bash.d/bash.scm
        fi
    fi
fi

if [[ -e $HOME/.guix-profile/bin/chezmoi ]]
then
    eval "$(chezmoi completion bash)"
fi

SSH_AUTH_SOCK="$(gpgconf --list-dirs agent-ssh-socket)"
export SSH_AUTH_SOCK

# TODO: Fix imv alias.
#
# if [ -n $WAYLAND_DISPLAY ]
# then
#     alias feh=imv
# fi

ssh_sudo()
{
    sshpass -p"$1" \
            ssh \
            -o UserKnownHostsFile=/dev/null \
            -o StrictHostKeyChecking=no \
            -q \
            -t \
            "$3" \
            -l "$2" \
            -- "set +o history; sudo --stdin --validate --prompt='' <<< \"$1\"; exec -a sudo sudo -i"
}

,s()
{
    sshpass -p"$1" \
            ssh \
            -o UserKnownHostsFile=/dev/null \
            -o StrictHostKeyChecking=no \
            "${@:2}"
}

psql()
{
    case "$1" in
        *)
            sudo -u postgres psql "$@"
            ;;
    esac
}

KUBECTL_WATCH_CGROUP="viddy"
export KUBECTL_WATCH_CGROUP

__lazy_kubectl()
{
    local word_count=${#COMP_WORDS[*]}
    local word_at_point="${COMP_WORDS[$COMP_CWORD]}"
    case $COMP_CWORD in
        *)
            if [[ $(type -t __start_kubectl) != function ]]
            then
                if [[ -f /home/oleg/.guix-profile/bin/kubectl ]]
                then
                    source <(/home/oleg/.guix-profile/bin/kubectl completion bash)
                fi
            fi
            ;;
    esac
}

complete -F __lazy_kubectl kubectl

__lazy_helm()
{
    local word_count=${#COMP_WORDS[*]}
    local word_at_point="${COMP_WORDS[$COMP_CWORD]}"
    case $COMP_CWORD in
        *)
            if [[ $(type -t __start_helm) != function ]]
            then
                if [[ -f /home/oleg/.guix-profile/bin/helm ]]
                then
                    source <(/home/oleg/.guix-profile/bin/helm completion bash)
                fi
            fi
            ;;
    esac
}

complete -F __lazy_helm helm

kubectl()
{
    case "$1" in
        master)
            command kubectl get node --output=json \
                | jq --raw-output '.items[] | select(.metadata.labels["node-role.kubernetes.io/master"] == "true") | .metadata.name'
            ;;
        cluster*)
            KUBECONFIG="/home/oleg/.kube/config-mjru-${1}" \
                kubectl \
                exec \
                --stdin=true \
                --tty=true \
                --namespace=kubernetes-tmuxifier \
                tmuxifier-0 \
                -- tmux at
            ;;
        drain)
            if [[ -z "$2" ]]
            then
                cat <<'EOF'
drain example:
    kubectl drain --ignore-daemonsets --delete-emptydir-data NODE
    kubectl delete pods --all-namespaces --field-selector 'spec.nodeName=NODE,metadata.namespace!=default'
EOF
            else
                command kubectl drain "${@:2}"
            fi
            ;;
        taint)
            if [[ -z "$2" ]]
            then
                cat <<'EOF'
drain example:
    kubectl taint node unschedulable=true:NoSchedule kube3
    kubectl taint node unschedulable- kube3
EOF
            else
                command kubectl drain "${@:2}"
            fi
            ;;
        noschedule)
            case "$2" in
                list)
                    command kubectl get nodes -o go-template='{{range $item := .items}}{{with $nodename := $item.metadata.name}}{{range $taint := $item.spec.taints}}{{if and (eq $taint.effect "NoSchedule")}}{{printf "%s\n" $nodename}}{{end}}{{end}}{{end}}{{end}}' \
                        | sort --version-sort
                    ;;
            esac
            ;;
        prometheus)
            command kubectl -n monitoring get secret prometheus-kube-prometheus-stack-prometheus -o json \
                | jq -r '.data["prometheus.yaml.gz"]' \
                | base64 -d \
                | gunzip
            ;;
        reboot)
            (
                set -ex
                kubectl drain "$2" --ignore-daemonsets --delete-emptydir-data
                ansible "${2}.intr" -m reboot -a 'search_paths=/run/current-system/sw/bin'
                kubectl uncordon "$2"
            )
            ;;
        cilium)
            command kubectl --namespace kube-system get pods --selector=k8s-app=cilium
            ;;
        tmuxifier)
            case "$2" in
                --help)
                    echo TMUXIFIER_KUBERNETES_NAMESPACE=cert-manager kubectl tmuxifier mjru-cluster2
                    ;;
                mjru-cluster1-view)
                    flake="git+https://gitlab.intr/nixos/kubernetes#kubeconfig-view"
                    nix build --no-link "$flake"
                    TMUXIFIER_TMUX_OPTS="-L kubernetes-cluster1-view" \
                                       KUBECONFIG="$(nix path-info "$flake")/.kube/config" \
                                       tmuxifier s kubernetes
                    ;;
                mjru-cluster1)
                    TMUXIFIER_TMUX_OPTS="-L kubernetes-cluster1" \
                                       KUBECONFIG="${HOME}/.kube/config-mjru-cluster1" \
                                       tmuxifier s kubernetes
                    ;;
                mjru-cluster2)
                    TMUXIFIER_TMUX_OPTS="-L kubernetes-cluster2" \
                                       KUBECONFIG="${HOME}/.kube/config-mjru-cluster2" \
                                       tmuxifier s kubernetes
                    ;;
                host1)
                    TMUXIFIER_TMUX_OPTS="-L config-host1-k3s" \
                                       KUBECONFIG="${HOME}/.kube/config-host1-k3s" \
                                       tmuxifier s kubernetes
                    ;;
                home)
                    TMUXIFIER_TMUX_OPTS="-L kubernetes-home-k8s" \
                                       KUBECONFIG="${HOME}/.kube/config-home-k8s" \
                                       tmuxifier s kubernetes
                    ;;
                *)
                    tmuxifier s kubernetes
                    ;;
            esac
            ;;
        *)
            command kubectl "$@"
            ;;
    esac
}

__lazy_virtctl()
{
    local word_count=${#COMP_WORDS[*]}
    local word_at_point="${COMP_WORDS[$COMP_CWORD]}"
    case $COMP_CWORD in
        *)
            if [[ $(type -t __start_virtctl) != function ]]
            then
                if [[ -f /run/current-system/profile/bin/virtctl ]]
                then
                    source <(/run/current-system/profile/bin/virtctl completion bash)
                fi
            fi
            ;;
    esac
}

__lazy_glab()
{
    local word_count=${#COMP_WORDS[*]}
    local word_at_point="${COMP_WORDS[$COMP_CWORD]}"
    case $COMP_CWORD in
        *)
            if [[ $(type -t __start_glab) != function ]]
            then
                if [[ -f "${HOME}/.nix-profile/bin/glab" ]]
                then
                    source <("${HOME}/.nix-profile/bin/glab" completion)
                fi
            fi
            ;;
    esac
}

complete -F __lazy_glab glab

glab()
{
    case "$1" in
        *)
            command glab "${@:1}"
            ;;
    esac
}


__lazy_ipmi()
{
    local word_count=${#COMP_WORDS[*]}
    local word_at_point="${COMP_WORDS[$COMP_CWORD]}"
    case $COMP_CWORD in
        *)
            if [[ $(type -t __start_ipmi) != function ]]
            then
                if [[ -f "$HOME/.nix-profile/share/bash-completion/completions/ipmi" ]]
                then
                    source "$HOME/.nix-profile/share/bash-completion/completions/ipmi"
                fi
            fi
            ;;
    esac
}

complete -F __lazy_ipmi ipmi

ipmi()
{
    case "$1" in
        *)
            IPMI_PASSWORD="$(pass show majordomo/public/ipmi/ADMIN)" command ipmi "${@:1}"
            ;;
    esac
}

__lazy_cscli()
{
    local word_count=${#COMP_WORDS[*]}
    local word_at_point="${COMP_WORDS[$COMP_CWORD]}"
    case $COMP_CWORD in
        *)
            if [[ $(type -t __start_cscli) != function ]]
            then
                if [[ -f /run/current-system/profile/bin/cscli ]]
                then
                    source <(/run/current-system/profile/bin/cscli completion bash)
                fi
            fi
            ;;
    esac
}

complete -F __lazy_cscli cscli

__lazy_flux()
{
    local word_count=${#COMP_WORDS[*]}
    local word_at_point="${COMP_WORDS[$COMP_CWORD]}"
    case $COMP_CWORD in
        *)
            if [[ $(type -t __start_flux) != function ]]
            then
                if [[ -f /home/oleg/.guix-profile/bin/flux ]]
                then
                    source <(/home/oleg/.guix-profile/bin/flux completion bash)
                fi
            fi
            ;;
    esac
}

complete -F __lazy_flux flux

cscli()
{
    case "$1" in
        *)
            sudo cscli "${@:1}"
            ;;
    esac
}

herd()
{
    case "$1" in
        start)
            case "$2" in
                fzf)
                    service="$(sudo command herd status | awk '/ - / { print $NF }' | fzf)"
                    sudo command herd enable "$service"
                    sudo command herd start "$service"
                    ;;
                *)
                    command herd enable "${@:2}"
                    command herd start "${@:2}"
                    ;;
            esac
            ;;
        restart)
            case "$2" in
                mail)
                    for service in $(herd status | awk '/isync/ { print $NF }')
                    do
                        herd start "$service"
                    done
                    ;;
                *)
                    command herd restart "${@:2}"
                    ;;
            esac
            ;;
        *)
            command herd "$@"
            ;;
    esac
}

opensearch()
{
    case "$1" in
        index)
            viddy --differences --interval 10 "bash -c 'curl ${2:-opensearch.home}/_cat/indices?pretty | sort -k 3'"
            ;;
    esac
}

curl()
{
    new_args=()
    for var in "$@"
    do
        if [[ "$var" == *"https://api.majordomo.ru/"* ]] || [[ "$var" == *"https://api.maxhost.ru/"* ]]
        then
            json=true
            new_args+=(
                --header "Authorization: Bearer $(mjru-auth)"
                --header 'Content-Type: application/json'
                "$var"
            )
        elif [[ "$var" == *"https://api.hms.development.corp1.majordomo.ru/"* ]] || [[ "$var" == *"http://api.hms.development.corp1.majordomo.ru/"* ]]
        then
            json=true
            new_args+=(
                --header "Authorization: Bearer $(IHS_ENDPOINT=http://api.hms.development.corp1.majordomo.ru mjru-auth)"
                --header 'Content-Type: application/json'
                "$var"
            )
        elif [[ "$var" == *"https://api-dev.intr/"* ]] || [[ "$var" == *"https://api-dev.maxhost.ru/"* ]]
        then
            json=true
            new_args+=(
                --header "Authorization: Bearer $(IHS_ENDPOINT=https://api-dev.intr mjru-auth)"
                --header 'Content-Type: application/json'
                "$var"
            )
        elif [[ "$var" == *"https://kubernetes.intr"* ]] || [[ "$var" == *"https://kubernetes-cluster2.intr"* ]]
        then
            new_args+=(
                --cacert "${HOME}/src/gitlab.intr/office/ssl-certificates/kubernetes/ca.pem"
                --cert "${HOME}/src/gitlab.intr/office/ssl-certificates/kubernetes/admin.pem"
                --key "${HOME}/src/gitlab.intr/office/ssl-certificates/kubernetes/admin-key.pem"
                "$var"
            )
        elif [[ "$var" == *"https://kubernetes.home:6443"* ]]
        then
            new_args+=(
                --cacert /etc/kubernetes/pki/ca.pem
                --cert /etc/kubernetes/pki/admin.pem
                --key /etc/kubernetes/pki/admin-key.pem
                "$var"
            )
        else
	    new_args+=($var)
        fi
    done
    command curl "${new_args[@]}"
    if [[ $json == true ]]
    then
        echo
    fi
}

dig()
{
    for var in "$@"
    do
        case "$var" in
            *majordomo.ru|*.intr|172.16.*|*pwhost.ru|*fast-name.ru|*host-support.ru|*litename.ru|*vipname.su|*hoster24.ru)
                name_servers=(
                    ns1-mr.intr
                    ns2-mr.intr
                    ns1-dh.intr
                    ns2-dh.intr
                    ns.majordomo.ru
                    ns2.majordomo.ru
                    ns3.majordomo.ru
                    ns4.majordomo.ru
                    ns1.corp1.majordomo.ru
                    ns2.corp2.majordomo.ru
                    ns1.svc1.majordomo.ru
                    ns2.svc2.majordomo.ru
                    ns1.corp2.majordomo.ru
                    ns2.corp2.majordomo.ru
                    ns1.svc2.majordomo.ru
                    ns2.svc2.majordomo.ru
                    8.8.8.8
                    8.8.4.4
                )
                (
                    set -x
                    command dig "$@"
                )
                for name_server in "${name_servers[@]}"
                do
                    (
                        set -x
                        command dig "$@" "@${name_server}"
                    )
                    mapfile -t ip_addresses < <(command dig "$@" "@${name_server}" \
                                                    | jc --dig \
                                                    | jq --raw-output .[].answer[].data)
                    (
                        for ip_address in "${ip_addresses[@]}"
                        do
                            (
                                set -x
                                command dig -x "$ip_address" "@${name_server}"
                            )
                        done
                    ) | sort --version-sort
                done
                ;;
            *)
                command dig "$@"
                ;;
        esac
    done
}

scream()
{
    case "$1" in
        *)
            cat <<'EOF'
scream -i br154.154 -u -p 16400
EOF
            command scream "$@"
            ;;
    esac
}

kresd()
{
    case "$1" in
        clear)
            sudo socat - "UNIX-CONNECT:/var/cache/knot-resolver/control/$(pidof kresd)" <<< 'cache.clear()'
            ;;
        *)
            command kresd "$@"
    esac
}

sudo()
{
    case "$1" in
        herd)
            case "$2" in
                start)
                    case "$3" in
                        xorg-server)
                            if [[ -e /var/run/slim-vt7.auth ]]
                            then
                                echo "Removing '/var/run/slim-vt7.auth' file."
                                command sudo rm /var/run/slim-vt7.auth
                            fi
                            if [[ -e /var/run/slim-vt7.lock ]]
                            then
                                echo "Removing '/var/run/slim-vt7.lock' file."
                                command sudo rm /var/run/slim-vt7.lock
                            fi
                            command sudo herd enable xorg-server
                            command sudo herd start xorg-server
                            ;;
                        *)
                            command sudo herd enable "${@:3}"
                            command sudo herd start "${@:3}"
                            ;;
                    esac
                    ;;
                *)
                    command sudo herd "${@:2}"
                    ;;
            esac
            ;;
        *)
            command sudo "$@"
            ;;
    esac
}

PASSWORD_STORE_ENABLE_EXTENSIONS="true"
export PASSWORD_STORE_ENABLE_EXTENSIONS

PATH="${HOME}/bin":"${HOME}/.local/bin":"$(/usr/bin/env --ignore-environment sh --norc --noprofile -c 'unset PATH; export HOME=/home/oleg; export USER=oleg; source /etc/profile; printf "$PATH"')":"${HOME}/go/bin":"${HOME}/.npm-global/bin":/opt/gradle/bin:"${HOME}/perl5/bin":"${HOME}/.nix-profile/lib/openjdk/bin":"${HOME}/.nix-profile/bin":"$PATH"
export PATH

pactl_configure()
{
    echo pactl load-module module-ladspa-sink sink_name=compressor-stereo plugin=sc4_1882 label=sc4 control=1,1.5,401,-30,20,5,30
    echo pactl load-module module-null-sink media.class=Audio/Sink sink_name=obs-microphone channel_map=front-left,front-right
    echo pactl load-module module-ladspa-sink sink_name=compressor-stereo-family-17 plugin=sc4_1882 label=sc4 control=1,1.5,401,-30,20,5
}

htop()
{
    bash -c 'exec -a htop sudo htop'
}

if [[ -n $ALACRITTY_WINDOW_ID ]]
then
    if [[ ${EUID} == 0 ]]
    then
	PS1='\[\033[01;31m\]\h\[\033[01;34m\] \W\$\[\033[00m\] '
    else
	PS1='\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\$\[\033[00m\] '
    fi

    if type -p bat
    then
        # bat can be used as a colorizing pager for man, by setting the MANPAGER
        # environment variable as documented here.
        # https://github.com/sharkdp/bat#man
        MANPAGER="sh -c 'col -bx | bat --theme=ansi -l man -p'"
        export MANPAGER
        MANROFFOPT="-c"
        export MANROFFOPT
    fi
fi
