#!/bin/sh
#
# vim: ft=sh:sw=2:ts=2:sts=2:fdm=marker:fdl=0:noml:

# Set my preferred editor
# typeset -ga visual=(v)

# stdin/stdout yank/paste
# "${commands[vim]:-${EDITOR}}"

# # case ${WAYLAND_DISPLAY+w}${commands[wl-paste]+a}${DISPLAY+x}${commands[xclip]+a}${commands[xsel]+b} in
# case ${WAYLAND_DISPLAY+w}${commands[wl-paste]-+a}${DISPLAY+x}${commands[xclip]+a}${commands[xsel]+b} in
#   wa*) alias y='wl-copy' p='wl-paste' Y='wl-copy -p' P='wl-paste -p' ;;
#   *xa) alias y='xclip -sel clip -in' p='xclip -sel clip -out' Y='xclip -in' P='xclip -out' ;;
#   *xb) alias y='xsel -b' p='xsel -b -o' Y='xsel' P='xsel -o' ;;
#   *) alias Y='>> ~/.clip' p='cat ~/.clip'
#     alias Y='>> ~/.clip' P='cat ~/.clip'
# esac

# quick access to zshrc, aliases, and history
# ez(){
#   # local arg
#   visual $ZDOTDIR/(.|)*${^@}*
# }
# alias ezrc='$visual ${ZDOTDIR:-$HOME}/.zshrc'
# alias ezshrc='$visual ${ZDOTDIR:-$HOME}/.zshrc'
# eal() {
# 	[ -n "${+1}" ] && "${visual:-}" ${(%):-%x} -c "/\<$1=" ||
#     "${visual:-}" ${(%):-%x}
# }
# sched +0 compdef _aliases eal

# alias ehist='${visual} ${HISTFILE}'
alias h='history'
alias a='alias'

# kinda hacky:
# if so do-something
alias so='((!$?));'
# pass secret on command line
# _zshrc_getpass(){
#   typeset -g __PASS
#   sched +0 unset __PASS
#   read -s '__PASS?>'
# }
# functions -Ms __getpass 1 1 .zshrc.getpass
# alias -g getpass='${$((__getpass())):+$__PASS}'
# Just show arguments
# ::(){
#   (($#)) && printf '%q\n' "$@"
#   :
# }

# choose something
# sel(){
# 	local -i i=$@[(i)(-|--)]
# 	local REPLY x a=($@[1,i])
# 	shift i
# 	select x;$a $x
# }

# Reply to args
# alias r2a='set -- "${(@)reply}"'

# simple export wrapper for export1 NAME $~glob(Y1)
export1(){
  [ "$1" = "[[:WORD:]]##" ] && export "$1"="$2"
}

#  ls aliases
# alias ls='ls --color=auto --classify --human-readable'
# alias l=$aliases[ls]' -l'
# alias lA=$aliases[ls]' --almost-all'
# alias la=$aliases[ls]' --all'
# alias lls=$aliases[ls]' -l --sort=size'
# alias ll='ls -l'
# alias lS=$aliases[ls]' --sort=size --size'
# alias sl=$aliases[ls]' --reverse'     # no steam locomotive here

# alias lt=$aliases[ls]' --sort=time'
# alias lct=$aliases[lt]' --time=ctime'
# alias lat=$aliases[lt]' --time=atime'
# alias lT=$aliases[lt]' --reverse'
# alias lcT=$aliasesl[lt]' --time=ctime --reverse'
# alias laT=$aliases[lt]' --time=atime --reverse'
# alias lsd='ls -C | column --output-width=$COLUMNS --table | lolcat'

# §() { ls --color -C * "$@" | less -R; } # depth=1

# sudo
# alias _='sudo'
# alias _i='sudo --login'
# alias _u='sudo su'
# alias _e='sudoedit'
# compdef gksudo='sudo'

# Grep aliases
# shellcheck disable=SC2262,SC2263
if command -v rg >/dev/null 2>&1; then
  # trim to $COLUMNS only when not in a pipeline and we have the space for a preview
  alias rg='rg --max-columns=$((COLUMNS > 60 && ! ZSH_SUBSHELL ? COLUMNS - 30 : 0))'
  alias rj='rg --json'
  rgl() { rg --pretty "$@" | less -RF; }
  rgless() { rg --pretty "$@" | less -RF; }
  RG() { rg --pretty "$@" | less -RF; }
  # sched +0 compdef _rg {rgl,rgless,RG}='rg --pretty'
else
  alias grep='grep --color'
  # use grep as a cheap rg/ag replacemnet
  alias ag='grep -R -n -H --exclude-dir={.git,.svn,CVS}'
  alias rg='grep -R -n -H --exclude-dir={.git,.svn,CVS}'
  alias sgrep='grep -R -n -H -C 5 --exclude-dir={.git,.svn,CVS}'
  grepl() { grep --color=always "$@" | less -R; }
  # sched +0 compdef _grep grepl='grep --color=always'
fi

# fd / find
alias find='noglob find'
if [ -n "${+commands[fd]}" ]; then
  alias f='noglob fd --glob'
  alias fd='noglob fd --glob --type directory'
  alias ff='noglob fd --glob --type file'
  alias fl='noglob fd --glob --type symlink'
else
  alias f='noglob find .'
  alias fd='noglob find . -type d -name'
  alias ff='noglob find . -type f -name'
  alias fl='noglob find . -type l -name'
fi


alias m=run-help
alias z=zsh b=bash c=cat
T() { tree -C "$@" | less -RF; }
sched +0 compdef _tree T
alias mz='man zshall'
# alias {Z,ZZ}='exec zsh'
alias Z='exec zsh'
alias ZZ='exec zsh'

# {{{ File operations
zmodload zsh/files # zsh versions of mv, rm, mkdir, etc
alias rm='rm -s'   # zsh extension, enable paranoid behavior
alias trash='gio trash'
alias mv='mv -i'
alias rscp='rsync -azP --human-readable --info=flist0,progress2,stats1'
# shellcheck disable=SC2312
RSCP() {
  rsync -aP "${1:-desktop.zt}:$(print -P %~)/${2:-.}/*" "${2:-.}"
}
# }}}
# {{{ ZSH suffix magic
#(){
#  autoload -Uz zsh-mime-setup zsh-mime-handler
#  [[ -r $1 ]] &&
#    source $1
#  if ! (( $+zsh_mime_handlers )); then
#    zsh-mime-setup
#    {
#      alias -Ls
#      typeset -p zsh_mime_handlers zsh_mime_flags
#    } >| $1
#  fi
#} ${XDG_CACHE_HOME:-$HOME/.cache}/zsh-mime-cache.zsh
## open browser on urls
#[[ "$BROWSER"  ]] && alias -s {htm,html,de,org,net,com,at,cx,nl,se,dk}=$BROWSER
#alias -s {cpp,cxx,cc,c,hh,h,inl,asc,md,txt,TXT,tex}='$visual'
#[[ "$XIVIEWER" ]] && alias -s {jpg,jpeg,png,gif,mng,tiff,tif,xpm}=$XIVIEWER

#[[ $commands[mpv] ]] && alias -s {ape,avi,flv,m4a,mkv,mov,mp3,mp4,mpeg,mpg,ogg,ogm,rm,wav,webm}=mpv

##read documents
#alias -s pdf=zathura ps=gv dvi=xdvi chm=xchm djvu=djview

##list whats inside packed file
#alias -s zip="unzip -l" rar="unrar l" tar="tar tf" tar.gz="echo " ace="unace l"
# }}}
# {{{ Android / TTS
if [ -n "${+ANDROID_DATA}" ]; then
  alias tts=termux-tts-speak
  alias ssh=ssha
elif [ -n "${+commands[pico2wave]}" ]; then
  tts() {
    f=$(mktemp --suffix=.wav)
    cleanup() { rm "${f}"; exit; }
    trap cleanup INT
    pico2wave -w "${f}" -- "$*"
    paplay "${f}"
    rm "${f}"
  }
  alias tts='noglob tts'
elif [ -n "${+commands[mimic]}" ]; then
  tts() { mimic "$*" play; }
  alias tts='noglob tts'
fi
# }}}
# {{{ Terminal utils
# (){
#   local field
#   for field (r w x){
#     alias -- "-$field=command chmod -$field"
#     alias -- "+$field=command chmod u+$field,g+$field"
#   }
# }
# }}}
# {{{ git: use aliases in gitconfig
alias g='git'
alias gs='git s' # tired of ghostscript on accident
# }}}
# {{{ fzf / tmux
# shellcheck disable=SC2034
if [ -n "${+TMUX}" ] && FZF_TMUX=1; then
  # Use tmux version if in tmux session
  alias fzf='fzf-tmux'

  # optional prefix
  # shellcheck disable=SC3033
  :neww() {
    tmux "$0" "$@"
  }
  # :neww :new-window(){
  #   tmux "$0" "$@"
  # }
fi
# fzf uses $SHELL to expand this
export FZF_DEFAULT_COMMAND='setopt extendedglob; p=${PWD:P}; locate "${p//(#m)\*\?\[\]/\\$MATCH}*" | cut -b$(( $#p + 2 ))-'
alias fzfa=$aliases[locate]' \* | fzf'
# }}}
# {{{ user-mount using udisksctl
alias ud=udisksctl
udm() {
  cd "$(udisksctl mount -b "$@" | tee /dev/stderr | sed 's/.* at \(.*\)$/\1/')"
}
udum() { # unmount by /dev/ or by mount path
  udisksctl unmount -b "$@" || udisksctl unmount -p "$@"
}
sched +0 compdef _mount udm=mount
sched +0 compdef _mount udum=umount
# }}}
# {{{ Some path functions
sched +0 compdef _files readlink
# if an executable expects to be launched in its directory
cdex() {
  local name
  [[ -f "$1" ]] && name="${1:P}" || name=${commands[$1]:-$1}
  cd "${name:P:h}"; "$name" "${@:2}"
}

# }}}
# {{{ grc colouring
alias GRC='grc -es'
alias LA='acol ls -lFAhb --color'
alias LS='acol ls -lFhb --color'
alias df='GRC df -hT'
alias dig='GRC dig'
alias docker='GRC docker'
alias docker-machine='GRC docker-machine'
alias env='acol env'
alias gcc='gcc -fdiagnostics-color=auto'
alias ip='ip -color=auto'
alias lsblk='acol lsblk'
alias lspci='acol lspci'
alias mount='acol mount'
alias lsmount='command mount | rg --color=never "^/" | acol -i -o mount'
alias nmap='acol nmap'
alias ping='GRC ping'
alias ps='GRC ps --columns $COLUMNS'
alias traceroute='GRC traceroute'
lsl() { grc ls -lFhb "$@" --color | less -R; }
sched +0 compdef _ls lsl='ls -lFhb'
# }}}
# {{{ other colouring
hi() { highlight -O ansi "$@" 2>/dev/null | less -R -F; }
# }}}
# {{{ UU: update everything
# tmux split git updates from package-manager udpates
if [ -n "${+TMUX}" ]; then
  if [ -n "${+commands[pikaur]}" ]; then
    alias UU='tmux split git-all -w pu; nice -n10 pikaur -Syu'
    alias pikaur='nice -n10 pikaur'
  elif [ -n "${+commands[pkg]}" ]; then
    alias UU='tmux split git-all -w pu; nice -n10 pkg update'
  elif [ -n "${+commands[apt]}" ]; then
    alias UU='tmux split git-all -w pu; sh -c "sudo apt update && sudo apt full-upgrade"'
  fi
  # shellcheck disable=SC2154
  alias peek='tmux split-window -p 30 ${EDITOR:-vi}'
else
  if (( $+commands[pikaur] )); then
    alias UU='tmux new git-all -w pu \; split nice -n10 pikaur -Syu'
    alias pikaur='nice -n10 pikaur'
  elif (( $+commands[pkg] )); then
    alias UU='tmux new git-all -w pu \; split nice -n10 pkg update'
  elif (( $+commands[apt] )); then
    alias UU='tmux new git-all -w pu \; split sh -c "sudo apt update && sudo apt upgrade"'
  fi
fi
# }}}
# {{{ wrappers/defaults
ncsh() {
  stty raw -echo
  ncat "$@"
  stty -raw echo
}
# Shortened python
alias py{,3}=python3

# Read comfortably
human_readable() {
  local TMPPREFIX=$XDG_RUNTIME_DIR/tmp TMPSUFFIX=.txt
  nvim +'set wrap linebreak nospell laststatus=0' ${@:-=(<&0)}
}
alias sys='systemctl --user'
alias Sys='systemctl'
alias jfeu='journalctl --user -xfeu'
alias Jfeu='journalctl -xfeu'
alias view=human-readable

alias nmtui='NEWT_COLORS="root=black,black;window=black,black;border=white,black;listbox=white,black;label=blue,black;checkbox=red,black;title=green,black;button=white,red;actsellistbox=white,red;actlistbox=white,gray;compactbutton=white,gray;actcheckbox=white,blue;entry=lightgray,black;textbox=blue,black" nmtui'
alias htip='HTOPRC=$HOME/.config/htop/minrc htop'
alias htap='HTOPRC=$HOME/.config/htop/maxrc htop'
alias htup='HTOPRC=$HOME/.config/htop/infrc htop'

alias pycalc='python3 -ic "
from math import *
import cmath as C
try:
    import numpy as np
except:
    pass
π, τ = pi, tau
i, j = 1j, 1j
"'
# ℝ by default
alias rust-c='rustc --out-dir build -O'
alias zcalc='IFS=, noglob zcalc'
gc_c() {
  dir=${1:h}/build
  mkdir -p "$dir"
  gcc -O3 "$1" -o "$dir/${${1:t}%.*}" "${@:2}"
}
gh_c() { ghc -Odph -dynamic "$1" -o "build/${1%.*}" -odir .build -hidir .build -tmpdir . "${@:2}"; }

alias qn="$visual ~/Sync/default/notes/quicknote.md"
xevkb() { xev -event keyboard "$@" | egrep -o '(keycode(.)+\)|XLookup.+[1-9].+)'; }
compdef _x_utils xevkb='xev -event keyboard'
splitarray() {# Usage: splitarray name delimiter [string]
  if [ $# -le 2 ]; then
    printf '%s\n' "Usage: $0 ARRAY_NAME DELIMITER [STRING]" '' \
    'If [STRING] is not provided, defaults to stdin'
    return
  fi
  # typeset -a $1=("${(@ps[$2])"${3:-"$(<&0)"}"}")
}
']'(){
  local MATCH MBEGIN MEND
  [ "${(Oa@)argv[1,-2]}" "${argv[-1]//(#m)[\[\]]/${(#)$((6 ^ #MATCH))}}"
}
'='() case $1 {
  @|-|--) set -- "${@:2}" ;;
  -*) eval "typeset ${1}ga $2"'=("${@:3}")' ;;
  *) eval 'typeset -ga '$1'=("${@:2}")'
}
curls() { # for calling curl on multiple urls with the same options

  # Get start of flags/options
  local -i idx='argv[(i)-*]'
  if ((idx < 2)); then
    print -u2 "Usage: $0 [ URL [ URL ...] ] [[ CURL OPTS ]]"
    return 1
  fi

  # apply curl options to each url
  local curlopts=("${@[idx,-1]}") args=()
  local arg
  for arg (${@[1,idx-1]}) {
    args+=("${(@)curlopts}" $arg --next)
  }

  # remove last --next flag
  curl "${(@)args[1,-2]}"
}
# }}}
# {{{ *TeX
tex2txt() {
  cmd=(pandoc -f latex -t plain)
  if (($#)); then
    $cmd <<< "\$$*\$"
  else
    $cmd
  fi
}
alias texmk='latexmk'         # default
alias texc='latexmk -c -norc' # leave output files (*.dvi/ps/pdf)
alias texC='latexmk -C -norc' # leave only *.tex files
# }}}
# {{{ _gnu_generic (i.e.: provides --help)
compdef _gnu_generic zathura
compdef _gnu_generic steamleaderboard
# }}}
# {{{Vim muscle memory
alias :q='exit'
alias :wq='exit'
alias :x='exit'
alias :e='${visual}'
alias :sp='${visual} -o'
alias :vsp='${visual} -O'
# }}}
loopback() { # {{{
  pactl load-module module-loopback "source=$(
    pactl list sources | awk '/Name:/{print $2}' | fzf --prompt='Source: '
  )" "sink=$(
    pactl list sinks | awk '/Name:/{print $2}' | fzf --prompt='Sink: '
  )"
}
# }}}

# TODO: move to misc-scripts/make config file
alias qr='qrencode -t UTF8'

fillscreen(){
  set -- "$*"
  print -rn ${(pl[COLUMNS*LINES][$1])}
  read -k1 _
}
