#!/bin/sh
export ACP_SHRC=1

if [ "${ZSH_VERSION-none}" != "none" ]; then
        emulate sh -c 'source /etc/profile'
fi

PATH="/usr/sbin:/sbin:/usr/bin:/bin"
for dir in  $HOME/bin \
            $HOME/.cargo/bin \
            $HOME/.gem/ruby/2.6.0/bin \
            $HOME/opt/centos-git-common \
            /usr/X11R7/bin \
            /usr/X11R6/bin \
            /usr/local/sbin \
            /usr/local/bin \
            /usr/pkg/sbin \
            /usr/pkg/bin \
            /usr/games \
            /usr/local/heirloom-doctools/bin \
            /usr/pkg/heirloom-doctools/bin \
            /var/lib/snapd/snap/bin \
            /app/bin \
            /snap/bin \
            /usr/dt/bin \
    ; do
    if [ -d "$dir" ]; then
        PATH="$PATH:$dir"
    fi
done
export PATH

MANPATH="/usr/share/man"
for dir in  $HOME/.local/share/man \
            /usr/X11R6/man \
            /usr/X11R7/man \
            /usr/local/man \
            /usr/pkg/man \
            /usr/local/share/man \
            /usr/local/heirloom-doctools/man \
    ; do
    if [ -d "$dir" ]; then
        MANPATH="$MANPATH:$dir"
    fi
done
export MANPATH

umask 0022

set -o emacs
set -o noclobber

# Locale and language.
## Clear the existing locale settings and set options I always want.
export LC_ALL=''
export TIME_STYLE="long-iso"       # Used by GNU 'ls'.
## Set the default language.
acctsvclang=$(dbus-send \
    --system \
    --print-reply=literal \
    --dest=org.freedesktop.Accounts \
    $(dbus-send \
        --system \
        --print-reply=literal \
        --dest=org.freedesktop.Accounts \
        --type=method_call \
        /org/freedesktop/Accounts \
        org.freedesktop.Accounts.FindUserById int64:$(id -u) \
        2>/dev/null) \
    org.freedesktop.DBus.Properties.Get \
    string:org.freedesktop.Accounts.User \
    string:Language \
    2>/dev/null \
    | awk '{print $2}')
if [ -n "$acctsvclang" ]; then
    LANG=$acctsvclang
elif [ -r "$HOME/.config/locale.conf" ]; then
    . "$HOME/.config/locale.conf"
elif [ -r "$HOME/.config/user-dirs.locale" ]; then
    LANG="$(cat $HOME/.config/user-dirs.locale).UTF-8"
fi
unset acctsvclang
case "$LANG" in
    "en_GB.UTF-8")
        LANGUAGE="en_GB:en"
        PAPERSIZE="a4"
        ;;
    "en_CA.UTF-8")
        LANGUAGE="en_CA:en"
        PAPERSIZE="letter"
        ;;
    "fr_FR.UTF-8")
        LANGUAGE="fr_FR:fr"
        PAPERSIZE="a4"
        ;;
    "fr_CA.UTF-8")
        LANGUAGE="fr_CA:fr"
        PAPERSIZE="letter"
        ;;
    *)
        LANG="en_GB.UTF-8"
        LANGUAGE="en_GB:en"
        PAPERSIZE="a4"
        ;;
esac
if [ -x /usr/bin/locale ] && [ $(locale -a 2>/dev/null | sed 's/.utf8$/.UTF-8/' | grep ${LANG-invalid} | wc -l) -eq 0 ]; then
    LANG=C
    LANGUAGE=C:en
fi
export LANG
export LANGUAGE
export PAPERSIZE
## Set the other language options to ${LANG}.
export LC_COLLATE="$LANG"          # Alphabetic sorting.
export LC_CTYPE="$LANG"            # Interpretation of byte sequences.
export LC_IDENTIFICATION="$LANG"   # Locale metadata (GNU).
export LC_MEASUREMENT="$LANG"      # Units of measure -- metric/imperial (GNU).
export LC_MESSAGES="$LANG"         # Language that messages are displayed in.
export LC_NAME="$LANG"             # Salutations and titles (GNU).
export LC_NUMERIC="$LANG"          # Formatting for non-monetary numbers.
export LC_TIME="$LANG"             # Time format.
export LC_ADDRESS="$LANG"          # Postal address (GNU).
export LC_MONETARY="$LANG"         # Currency display.
export LC_PAPER="$LANG"            # Standard paper size -- A4 or Letter (GNU).
export LC_TELEPHONE="$LANG"        # Formats for telephone services (GNU).

# Other exports.
export ANSIBLE_NOCOWS=1
export CHROMIUM_FLAGS="--incognito"
export DEBEMAIL="anthony@acperkins.com"
export DEBFULLNAME="Anthony Perkins"
export EDITOR=vi
export POWERSHELL_TELEMETRY_OPTOUT=1
export PYTHONWARNINGS="ignore::UserWarning"

PS1="$ "
if [ "${HOST-invalid}" != "invalid" ]; then
    HOST="$(hostname 2>/dev/null || cat /etc/hostname)"
fi
if test $(id -u) -eq 0; then
    export PS1="${HOST-localhost%%.*}# "
else
    export PS1="${HOST-localhost%%.*}$ "
fi
if test -x /usr/bin/tty; then
    export GPG_TTY=$(tty)
fi

if [ "${BASH-none}" != "none" ]; then
    HISTCONTROL=ignorespace:ignoredups
    shopt -s histappend
    bind '"\e[1;5C": forward-word'
    bind '"\e[1;5D": backward-word'
    bind '"\e[A": history-search-backward'
    bind '"\e[B": history-search-forward'
    bind 'set bell-style none'
    bind 'set completion-ignore-case on'

    if test $(id -u) -eq 0; then
        export PS1="\[\033[01;32m\]\h\[\033[01;31m\]\#\[\033[00m\] "
    else
        export PS1="\[\033[01;32m\]\h\[\033[01;34m\]\$\[\033[00m\] "
    fi
fi

if [ "${ZSH_VERSION-none}" != "none" ]; then
    # Command history.
    autoload -Uz compinit && compinit
    autoload -U history-search-end
    zle -N history-beginning-search-backward-end history-search-end
    zle -N history-beginning-search-forward-end history-search-end
    bindkey "^[[A" history-beginning-search-backward-end
    bindkey "^[[B" history-beginning-search-forward-end
    bindkey "^[OA" history-beginning-search-backward-end
    bindkey "^[OB" history-beginning-search-forward-end

    bindkey "^[[1;5C" forward-word  # Ctrl-Right
    bindkey "^[[1;5D" backward-word  # Ctrl-Left
    bindkey "^[[3;5~" delete-char  # Ctrl-Del
    bindkey "^[[3~" delete-char  # Del
    bindkey "^[x" undefined-key  # Alt-X
    export HIST_IGNORE_SPACE=yes
    export HISTFILE=$HOME/.zsh_history
    export HISTSIZE=1000000
    export SAVEHIST=1000000
    setopt EXTENDED_HISTORY
    setopt HIST_IGNORE_ALL_DUPS
    setopt HIST_IGNORE_SPACE
    setopt PROMPT_SUBST
    setopt SHARE_HISTORY
    setopt no_list_ambiguous

    zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'

    if test $(id -u) -eq 0; then
        export PS1="%F{10}%m%F{9}#%f "
    else
        export PS1="%F{10}%m%F{12}$%f "
    fi
fi

LSOPTIONS="-F"
if ls --color=auto /dev/null 2>/dev/null 1>/dev/null; then
    LSOPTIONS="$LSOPTIONS --color=auto"
fi
if [ "$(uname -s)" = "FreeBSD" ]; then
    LSOPTIONS="$LSOPTIONS -G"
fi
if [ "$(uname -s)" = "Linux" ]; then
    alias df="df -x squashfs"
fi

alias 7zencrypt="7z a -t7z -p -mhe"
alias adoc="asciidoctor -a stylesheet=$HOME/.asciidoctor.css"
alias alu="apt list --upgradable"
alias asdo="apt source --download-only"
alias aurmake="makepkg -irs"
alias btrdf="sudo btrfs filesystem usage"
alias cal="ncal -w"
alias ec="emacsclient -c"
alias en="emacsclient -nw"
alias f="fossil"
alias ip="ip -c"
alias ll="/bin/ls -l"
alias ls="/bin/ls $LSOPTIONS"
alias now="date +%Y%m%dT%H%M%S%z"
alias nowu="date -u +%Y%m%dT%H%M%SZ"
alias pacup="sudo pacman -Syu --needed"
alias streamenc="openssl aes-256-cbc -pbkdf2 -in - -out - -e"
alias streamdec="openssl aes-256-cbc -pbkdf2 -in - -out - -d"
alias ta="$HOME/opt/textadept/textadept"
alias wgr="wordgrinder"
alias ytmp3="youtube-dl -q -x --audio-format=mp3"
alias zlu="zypper list-updates"

# QEMU aliases
alias qemu-486="qemu-system-i386 -machine isapc,accel=kvm -cpu 486 -m 16 -vga cirrus -soundhw sb16 -nic none" # -nic user,model=ne2k_isa
alias qemu-p1="qemu-system-i386 -machine pc,accel=tcg -cpu pentium -m 64 -vga cirrus -soundhw sb16 -nic none" # -nic user,model=ne2k_isa
alias qemu-p3="qemu-system-i386 -machine pc,accel=kvm -cpu pentium3 -m 256 -vga cirrus -usb -soundhw sb16 -nic none" # -nic user,model=rtl8139
alias qemu-core2="qemu-system-x86_64 -machine q35,accel=kvm -cpu core2duo -m 2048 -vga qxl -usb -soundhw hda -nic none" # -nic user,model=e1000

if [ ! -d "$HOME/.local/bin" ]; then
    mkdir -p "$HOME/.local/bin"
fi

# Alias vi to vim if it is installed.
if [ -x /usr/bin/vim ] || [ -x /usr/local/bin/vim ] || [ -x /usr/pkg/bin/vim ]; then
    alias vi="vim"
fi

# Set up GOPATH.
export GOPATH="$HOME/data/go"
if [ -x $HOME/opt/go/bin/go ] || [ -x /usr/bin/go ] || [ -x /usr/local/bin/go ]; then
    if [ ! -d "$GOPATH" ]; then
        mkdir -p "$GOPATH/bin"
        mkdir -p "$GOPATH/pkg"
        mkdir -p "$GOPATH/src"
    fi
    if [ -x $HOME/opt/go/bin/go ]; then
        export GOROOT="$HOME/opt/go"
        export PATH="$PATH:$GOROOT/bin"
    fi
    export PATH="$PATH:$GOPATH"
fi

# Useful aliases for Podman and Docker
alias prun="podman run --rm -it"
alias prunx="podman run --security-opt label=disable -v /tmp/.X11-unix/:/tmp/.X11-unix/ -e DISPLAY=\"unix\$DISPLAY\" -v /run/user/$(id -u)/:/run/user/$(id -u)/ -e XDG_RUNTIME_DIR=/run/user/$(id -u) -e PULSE_SERVER=/run/user/$(id -u)/pulse/native --ipc host"
alias drun="sudo docker run --rm -it"
alias drunx="sudo docker run -v /tmp/.X11-unix:/tmp/.X11-unix:ro -e DISPLAY=\"unix\$DISPLAY\""

# Desktop files (used by desktop environments within both X11 and Wayland) are
# looked for in XDG_DATA_DIRS; make sure it includes the relevant directory for
# snappy applications' desktop files.
snap_xdg_path="/var/lib/snapd/desktop"
if [ -n "${XDG_DATA_DIRS##*${snap_xdg_path}}" ] && [ -n "${XDG_DATA_DIRS##*${snap_xdg_path}:*}" ]; then
    export XDG_DATA_DIRS="${XDG_DATA_DIRS}:${snap_xdg_path}"
fi

mkcd () {
    if [ $# -ne 1 ]; then
        echo "mkcd: incorrect arguments (one directory required)." >&2
        return 1
    else
        mkdir -p "$1"
        cd "$1"
    fi
}

termtitle () {
    echo -en "\033]0;$1\007"
}

linapm () {
    cat /sys/class/power_supply/BAT0/{status,capacity}
}

cman () {
    # md: start bold
    # us: start underline
    # ue: end underline
    # me: end bold, blink, and underline
    env MANPAGER=less \
        LESS_TERMCAP_md=$'\e[1;36m' \
        LESS_TERMCAP_me=$'\e[0m' \
        LESS_TERMCAP_us=$'\e[4;32m' \
        LESS_TERMCAP_ue=$'\e[0m' \
        /usr/bin/man "$1"
}

xa () {
    OUT=$(xrandr --listactivemonitors | awk 'NR!=1{print " "$NF" "}')
    for monitor in "${OUT}"; do
        m=$(echo $monitor | sed 's/ //g')
        xrandr --output $m --auto
    done
}

lastreboots () {
    journalctl | grep -A 1 -- '-- Reboot --' | grep -v '^--' | awk '{print $1, $2, $3}'
}

emacsro () {
    emacs $1 -f view-mode
}

tm () {
    if tmux list-session 2>/dev/null 1>/dev/null; then
        tmux -2 attach-session
    else
        tmux -2 new-session
    fi
}

qemuquick () {
    qemu-system-x86_64 -nodefaults -readconfig $1
}

if [ -x /usr/bin/yum ] && [ ! -x /usr/bin/dnf ]; then
    alias dnf='yum'
fi

if test -n "$DISPLAY" && test -x /usr/bin/gvim; then
    export EDITOR="/usr/bin/gvim"
fi

if [ -x /usr/bin/svnlite ] && [ ! -x /usr/local/bin/svn ]; then
    alias svn='svnlite'
    alias svnadmin='svnliteadmin'
    alias svndumpfilter='svnlitedumpfilter'
    alias svnlook='svnlitelook'
    alias svnmucc='svnlitemucc'
    alias svnrdump='svnliterdump'
    alias svnserve='svnliteserve'
    alias svnsync='svnlitesync'
    alias svnversion='svnliteversion'
fi

case $- in
    *i*)
        # Shell is interactive
        printf "\033[7m"
        uname -sr
        printf "\033[0m"
        if [ -r /etc/os-release ]; then
            echo "    $(. /etc/os-release; echo $NAME $VERSION)"
        fi
        ;;
    *)
        ;;
esac

if test -S "$SSH_AUTH_SOCK"  && test -r "$HOME/.ssh/id_ed25519" && [ $(ssh-add -l | egrep "acp-(home|work) \(ED25519\)" | wc -l) = 0 ]; then
    ssh-add "$HOME/.ssh/id_ed25519"
fi

if [ -r $HOME/.shrc.$(hostname -s 2>/dev/null || cat /etc/hostname) ]; then
    . $HOME/.shrc.$(hostname -s 2>/dev/null || cat /etc/hostname)
fi