# Source other files
[ -r ~/.prompt ] && . ~/.prompt
[ -r ~/.devspec ] && . ~/.devspec
[ -r ~/.config/colorscheme ] && . ~/.config/colorscheme

_COLOR_GUIX_OUT="${_BLD}${_RED}"
_COLOR_GUIX_OUT_SEP="${_PRP}"

[ "$TERM" == "screen.linux" ] && export TERM="screen"

export EDITOR="vim"
export TERM=xterm-256color

# History stuff
export HISTCONTROL=ignoredups:erasedups
export HISTFILESIZE=1000
export HISTSIZE=1000

export GPG_TTY=$(tty)

export MANPATH=/run/current-system/profile/share/man:/home/cobra/.guix-profile/share/man:/run/current-system/profile/share/man:/home/cobra/.guix-home/profile/share/man

clear() {
        printf '\033c' # faster than ncurses clear by a lot
}

# Other aliases
alias c='clear'
alias ls='ls --color=auto -FAh'
alias ll='ls -l'
alias nf='hyfetch'
alias ga='git add'
alias gc='git commit -sS'
alias gp='git push'
alias mpv='mpv --no-audio-display'
alias wv='swayhide mpv $($PASTE_COMMAND)'
alias curl='curl -L'
alias prof='profanity'
alias gomuks="http_proxy='socks5://127.0.0.1:9050' gomuks"
alias tut="http_proxy='socks5://127.0.0.1:9050' tut"
alias dico="dico -d en-wiktionary"

# Random string (passwords)
randstr() {
        tr -cd '[:graph:]' </dev/urandom | head -c ${1:-256}
}

# Get CPU usage
cpusage() {
        bc<<<"scale=3;$(ps aux | awk 'BEGIN {sum=0} {sum+=$3}; END {print sum}') / $(nproc --all)"
}

# Update and upgrade system
update() { eval "$UPDATE"; }

# Im too lazy to type
copy() {
        printf "%s" "$(</dev/stdin)" > >($COPY_COMMAND)
}

# URL-encode stdin
urlencode() {
        LC_COLLATE_OLD=$LC_COLLATE
        LC_COLLATE=C

        local TEXT="$(</dev/stdin)"
        local LENGTH="${#TEXT}"
        for (( i = 0; i < LENGTH; i++ )); do
                local c="${TEXT:$i:1}"
                case $c in
                        [a-zA-Z0-9.~_-]) printf '%s' "$c" ;;
                        *) printf '%%%02X' "'$c" ;;
                esac
        done
        LC_COLLATE=$LC_COLLATE_OLD
}

diffhome() { find . -type f -regex '\./\.[^g].*' -exec diff -q ~/{} {} 2> /dev/null \;; }

fixdh() {
        diffhome | while read -r _ SRC _ DEST _; do
                cp $SRC $DEST;
        done;
}

strlen() {
        N=$(wc -c <<< "$*")
        ((N--))
        printf '%u\n' "$N"
}

caption() {
        [ -z "$3" ] && {
                echo "Usage: caption [input] [output] [text...]"
                return 1
        }
        local FILE="$1"
        local OUT="$2"
        shift 2
        local TEXT="$*"
        local WIDTH="$(identify -format "%[w]\n" "$FILE" | head -n1)"
        local HEIGHT="$(identify -format "%[h]\n" "$FILE" | head -n1)"
        local FONT_SIZE="$(((HEIGHT+WIDTH)/20))"
        convert -gravity north \( -size "${WIDTH}x" -pointsize "$FONT_SIZE" -font 'Liberation-Sans-Bold' caption:"$TEXT" -gravity Center -extent "${WIDTH}x" \) "$FILE" -append "$OUT"
}

captionvid() {
        [ -z "$3" ] && {
                echo "Usage: captionvid [input] [output] [text...]"
                return 1
        }
        rm /tmp/caption.*.png
        FPS="$(ffmpeg -i "$1" 2>&1 |grep fps | sed 's/.* \([0-9]\+\) fps.*/\1/')"
        IN="$1"
        OUT="$2"
        shift 2
        ffmpeg -i "$IN" "/tmp/caption.%02d.png"
        for i in /tmp/caption.*; do
                caption "$i" "$i-new.png" "$*"
        done
        ffmpeg -framerate $FPS -i "/tmp/caption.%02d.png-new.png" "$OUT"
        rm /tmp/caption.*.png
}

topbottom() {
        [ -z "$3" ] && {
                echo "Usage: caption [input] [output] [text...]"
                return 1
        }
        local FILE="$1"
        local OUT="$2"
        shift 2
        local WIDTH="$(identify -format "%[w]\n" "$FILE" | head -n1)"
        local HEIGHT="$(identify -format "%[h]\n" "$FILE" | head -n1)"
        local FONT_SIZE="$(((HEIGHT+WIDTH)/20))"
        convert -size "${WIDTH}x" -stroke black -strokewidth 3 -fill white -pointsize "$FONT_SIZE" -font 'Liberation-Sans-Bold' -gravity Center -extent "${WIDTH}x" -gravity north \( -annotate +0+0 "$1" \) -gravity south \( -annotate +0+0 "$2" \) "$FILE" -append "$OUT"
}

topbottomvid() {
        [ -z "$3" ] && {
                echo "Usage: captionvid [input] [output] [text...]"
                return 1
        }
        rm /tmp/caption.*.png
        FPS="$(ffmpeg -i "$1" 2>&1 |grep fps | sed 's/.* \([0-9]\+\) fps.*/\1/')"
        IN="$1"
        OUT="$2"
        shift 2
        ffmpeg -i "$IN" "/tmp/caption.%02d.png"
        for i in /tmp/caption.*; do
                topbottom "$i" "$i-new.png" "$1" "$2"
        done
        ffmpeg -framerate $FPS -i "/tmp/caption.%02d.png-new.png" "$OUT"
        rm /tmp/caption.*.png
}

playcd() {
        mpv --start=00:00:00.0000000 av://libcdio:/dev/cdrom --cache=yes
}

playdvd() {
        mpv --start=00:00:00.0000000 dvd:///dev/sr0 --cache=yes
}

gpginfo() {
        gpg --with-colons --import-options show-only --import
}

lc() {
        fc -nl $HISTCMD | sed 's/^\s*//'
}

baseto() {
        if [ $# -ge 3 ]; then
                local i="$1"
                local o="$2"
                shift 2
                bc <<< "obase=$o;$(($i#$*))"
        else
                local line i o n
                while read -r line; do
                        read -r i o n <<< "$line"
                        bc <<< "obase=$o;$(($i#$n))"
                done
        fi
}

rebash() { . ~/.bashrc; }
bashrc() { "$EDITOR" ~/.bashrc && rebash; }

uplot() {
        ssh vern "${1:-/opt/gnuplot/users/gnuplot.sh}; cat /opt/gnuplot/users/${1:-$(date -u -I)}.svg" > ${1:-$(date -u -I)}.svg
}


mnplot() {
        ssh mythos "${1:-/opt/gnuplot/gnuplot.sh}; cat /opt/gnuplot/${1:-$(date -u -I)}.svg" > ${1:-$(date -u -I)}.svg
}

vnplot() {
        ssh vern "${1:-/opt/gnuplot/net/gnuplot.sh}; cat /opt/gnuplot/net/${1:-$(date -u -I)}.svg" > ${1:-$(date -u -I)}.svg
}

vpplot() {
        ssh vern "${1:-/opt/gnuplot/power/gnuplot.sh}; cat /opt/gnuplot/power/${1:-$(date -u -I)}.svg" > ${1:-$(date -u -I)}.svg
}

inplot() {
        ssh iceberg "${1:-~/gnuplot/gnuplot.sh}; cat ~/gnuplot/${1:-$(date -u -I)}.svg" > ${1:-$(date -u -I)}.svg
}

cnplot() {
        ssh crescent "${1:-/opt/gnuplot/net/gnuplot.sh}; cat /opt/gnuplot/net/${1:-$(date -u -I)}.svg" > ${1:-$(date -u -I)}.svg
}

cpplot() {
        ssh crescent "${1:-/opt/gnuplot/power/gnuplot.sh}; cat /opt/gnuplot/power/${1:-$(date -u -I)}.svg" > ${1:-$(date -u -I)}.svg
}

reconf() {
        $PRIV -E guix system reconfigure /etc/guix-config/${HOSTNAME,,}.scm "$@"
}

hreconf() {
        guix home reconfigure $HOME/.config/guix/home-config.scm "$@"
}

geng() {
        < "$1" sed 's/\s*;.*//' | grep -ve '^$' -e '^T' | awk '{print "N"NR" "$0}' > "$2"
}

mkmshex() {
        FILE="${1%.*}"
        microscheme "$1"
        avr-gcc -B /run/current-system/profile/avr/lib/avr5 -mmcu="$2" -g -Os "$FILE".s -o "$FILE".elf
        avr-objcopy -Oihex "$FILE".o "$FILE".hex
}

uploadhex() {
        avrdude -C/run/current-system/profile/etc/avrdude.conf -v -p"$2" -carduino -P${3:-/dev/ttyS0} -U"flash:w:$1:i"
}

gshpkg() {
        local re='[\(]?\("([^"]*)"'
        if [[ "$GUIX_ENVIRONMENT" ]]; then
                local PACKAGES=($(while read -r line; do
                                [[ "$line" =~ $re ]] && printf '%s ' "${BASH_REMATCH[1]}"
                        done < $GUIX_ENVIRONMENT/manifest))
                echo ${PACKAGES[@]}
        fi
}