# Shell aliases & functions for Zsh, works almost completely for Bash as well

if test "$ZSH_NAME" = "zsh"; then
alias -g ___='"$(eval "$(fc -ln -1)" | tail -n 1)"'
alias -g G="| grp"
alias -g X="| xargs"
alias -g X1="| xargs -n 1"
fi

alias info='info --vi-keys'

xdh="$XDG_DATA_HOME"
xch="$XDG_CONFIG_HOME"
if test -d "$DATA"; then
  da=$(cd $DATA/_* && pwd)
  d1=$(cd $DATA/1* && pwd)
  d2=$(cd $DATA/2* && pwd)
  d3=$(cd $DATA/3* && pwd)
  d4=$(cd $DATA/4* && pwd)
fi 2>/dev/null

ulimit -c unlimited # Enable core dumps

which lsb_release >/dev/null && export DIST=$(lsb_release --id | cut -d'	' -f2) || true

unalias rd 2>/dev/null
rd() {
  test -d "$1" && find "$1" -type d -empty -printf "Removing %p\n" -delete || rm "$@"
}
rr() { mv "$@" /tmp }

alias j='jrnl'
alias jn='jrnl -to today | bat --style=plain --pager="less +G"'

# like "which", but shows contents if it resolves to a file
wh() {
  res=$(which "$@")
  test -r "$res" && b --plain "$res" || echo "$res"
}

alias logoff="loginctl terminate-user $USER"

# Some aliases
alias edgrub='sudoedit /etc/default/grub && sudo update-grub'
alias edenv='sudoedit /etc/environment'
alias edpart='sudoedit /etc/fstab && sudo findmnt --verify'

# Underline arg
highlight() { echo "$1" }

alias dedup='awk '"'"'!a[$0]++'"'"
edconf() {
	conf_cache_dir="$XDG_CACHE_HOME/edconf"
	conf_cache="$conf_cache_dir/files"
	conf_tmp="${conf_cache}.tmp"
	conf_extra="$XDG_CONFIG_HOME/edconf-extra"
	mkdir -p "$conf_cache_dir"
	touch "$conf_cache"
	# | xargs file | grep text | cut -d':' -f1 # this filters out non-text files, but it's ridiculously slow
	sel="$({ cat "$conf_cache"; test -f "$conf_extra" && cat "$conf_extra";
		fd --hidden --type file --size -1m --max-depth 1 . ~;
		fd --hidden --type file --size -1m --max-depth 3 . --full-path "$XDG_CONFIG_HOME" /etc } |
		  dedup | fzf -1 -0 --tiebreak=end,length --preview 'bat --color=always --style=numbers --line-range :200 {}' --query="$1" --history "$conf_cache_dir/searches")"
	test "$sel" && ((echo "$sel" | cat - "$conf_cache" | head -30 >"$conf_tmp" && mv "$conf_tmp" "$conf_cache") & edit "$sel")
}

CONFIG_SHELL_FUNCTIONS="${BASH_SOURCE[0]:-${(%):-%x}}"
alias r="reset && exec zsh"
edshell() {
	case $1 in
		("") file="$CONFIG_SHELL_FUNCTIONS";;
		(zsh) file="$CONFIG_ZSH/.zshrc";;
		(prof*) file="$HOME/.zprofile";;
		(*) file=$(find $CONFIG_SHELLS -name "$1*" | head -1);;
	esac
	checksum="$(md5sum $file)"
	$EDITOR $file
	test "$checksum" != "$(md5sum $file)" && source "$HOME/.zprofile" && exec $SHELL
}

edbin() {
  file="$(f=$(which $1) && test -f "$f" && echo $f || echo "$HOME/.local/bin/scripts/$1")"
  edit "$file"
  case "$file" in ($HOME*) yadm add "$file";; esac
}

alias l="ls -l --almost-all --human-readable --group-directories-first --file-type"
cd() {
  test ! -e "$1" && test $# -eq 1 && cd $DATA/$1* && return
  builtin cd $1 &&
    command ls --file-type --group-directories-first --color=always --format=vertical -w $COLUMNS | head -3
}

swap() {
	mv -n $1 $1.tmp
	mv -n $2 $1
	mv -n $1.tmp $2
}

# Task management & time tracking
t() {
  if test "$#" -eq 0 && which tn >/dev/null
  then tn
  else if test "$1" = "do"
    then test "$2" -gt 0 2>/dev/null && task mod sched:today "${@:2}" || task add sched:today "${@:2}"
    else task "$@"
    fi
  fi
}

alias tw='timew'
twsm() { timew summary $(date --date="Monday $1 week ago" -I) to tomorrow :ids ${@:2} }
alias twtest='( cp -r "$TIMEWARRIORDB" /tmp/tw-bak && TIMEWARRIORDB=/tmp/timewarriordb-test/$(date +%s) && mkdir -p "$TIMEWARRIORDB"/data && :> "$TIMEWARRIORDB"/timewarrior.cfg && $SHELL )'

# Quick shortcuts
alias c='clear'
alias v='edit'

alias lst='( last; last -f /var/log/wtmp.1 ) | grep -v "pts/" | tac | less +G'
alias lar='last | tac'

# Listen to loopback of mic
alias listen='pactl load-module module-loopback; read; pactl unload-module module-loopback'

alias browse-safe='sudo systemctl disable --now systemd-resolved && sudo rm -f /etc/resolv.conf && echo "nameserver 185.228.168.10" | sudo tee /etc/resolv.conf && sudo chattr +i /etc/resolv.conf'
alias browse-unsafe='sudo chattr -i /etc/resolv.conf && sudo mv /etc/resolv.conf /etc/resolv.conf.bak && sudo systemctl enable --now systemd-resolved && sleep 100 && browse-safe'

xo() {
  while test $# -gt 0; do
    xdg-open "$1"
    shift
  done
}
alias sqli='rlwrap sqlite3 -column -header -cmd .tables'
alias loc='noglob locate --basename'
alias uloc='noglob sudo updatedb && locate --basename'
alias syslog='less +F /var/log/syslog'
alias println='printf "\n"'
alias graphics='lspci -vnn | grep VGA --color=never && xrandr --listproviders'
alias vlch="vlc -H | ${PAGER:-less}"
alias usergroups="cat /etc/passwd | cut -d':' -f1 | xargs -n 1 id"
alias omd="(echo '#+OPTIONS: tags:nil'; xclip -o -selection clipboard) | pandoc -f org-auto_identifiers -t markdown --wrap preserve | xclip -filter"
alias mdo="pandoc -f gfm -t org --wrap preserve"
alias mdox="xclip -o -selection clipboard | mdo | xclip -filter"

alias gdiff='git diff --word-diff=color --word-diff-regex=. --no-index'

alias sc='sudo systemctl'
scs() { sudo systemctl status "*$1*" }
alias scu='systemctl --user'
alias scrw='sudo systemctl restart display-manager'

alias jcl='sudo SYSTEMD_LESS=FRKi journalctl --boot --no-hostname -e'
alias jc='jcl -u'
alias jcj='jcl -o json-pretty -u'

alias grp='grep --line-number --ignore-case --binary-files=without-match --directories=skip'
alias grpr='grp --recursive'
# Use grep and sed to replace $1 with $2 recursively
rpl() {
	grep --null --recursive --files-with-matches "$1" |
		xargs -0 sed -i "/${1}/{
			s//${2}/g
			w /dev/stdout
		}"
}


# Recover stray swap files from neovim
alias vrec="ls $XDG_DATA_HOME/nvim/swap | sed 's/\%/\//g' | sed 's|\(.*\)\..*|\1|' | head -1 | xargs -r nvim"
alias vrecd="ls $XDG_DATA_HOME/nvim/swap | head -1 | xargs -r -i mv {} /tmp"

unv() { strings $1 | sed 's/5$//' | dedup }

# Applications
alias dict="(builtin cd $XDG_DATA_HOME/dictcc && rlwrap perl dictcc-helper.pl)"
alias startMinecraftServer='curl https://ipinfo.io/ip | xclip -sel clip && cd ~/daten/games/sharedgames/minecraft/server && java -jar forge-1.12.2-14.23.5.2768-universal.jar -mx 8G'

test -d $HOME/.dropbox && dropbox_path="$(cat $HOME/.dropbox/info.json | grep -Po '"'"path"'"\s*:\s*"\K([^"]*)')"

# Add an "alert" alias for long running commands. Use like so: sleep 10; alert
#if [ command -v notify-send >/dev/null 2>&1 ]; then
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(echo "$history[$HISTCMD]" | sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
#fi

# Find zmv in man because I need to look it up all the time ^^
man() {
	(test "$1" = "zmv" && LESS="$LESS+/^ *zmv *\\[" /usr/bin/man zshcontrib) || /usr/bin/man "$@"
}

sedcomment() { sed -i 's/$1/#\0/' "${@:2}" }
seduncomment() { sed -i 's/#\($1\)/\0/' "${@:2}" }

updateDeps() {
	name="$1"
	pattern="$2"
	depth="4"
	case $name in
		gradle-wrapper.properties) depth=6;;
	esac
	shift 2
	oldversion="[0-9.]\+"
	while test $# -gt 1; do
		case "$1" in
			--pattern) oldversion="$2";;
			--version) version="$2";;
		esac
		shift 2
	done
	echo name $name depth $depth pattern $oldversion version $version
	find -maxdepth $depth -type f -name $name | while read f
	do  echo $f
		sed -i "s/\($pattern\)$oldversion/\1$version/gw /dev/stdout" $f
	done
}
alias updateKotlin="updateDeps build.gradle.kts 'kotlin(\"jvm\") version ' --version"
alias updateGradle='updateDeps gradle-wrapper.properties "services.gradle.org\/distributions\/gradle-" --version'
alias updateUtils='updateDeps build.gradle.kts '\''\"com.github.Xerus2000.util\", \".*\", \"'\'' --pattern '\''[^\"]\+'\'' --version'

# Kill all shell background processes
alias killbg='kill ${${(v)jobstates##*:*:}%=*}'

# Kil all Java processes except IDEA
# Pass "-9" to force-kill and "-q" to not output what has been killed
killJava() {
	pgrep -f 'java' | while read id
		do if [[ $(ps --no-headers -o cmd $id) != *"idea"* ]]; then
			[[ "$@" == "-q" ]] || echo "killing $(ps -p $id -o pid,cmd --width 350 --no-headers)"
			if [[ "$@" == "-9" ]]
			then kill -9 $id
			else kill $id
			fi
		fi; done
}

clearNpmCache() {
	rm -rf $TMPDIR/react-*
	rm -rf node_modules/
	npm cache verify
	npm install
}

# NAVIGATION

alias rcd="cd $PWD"
cdd() { cd "$@" 2>/dev/null || cd "$(dirname "$1")" "${@:2}" }

# Go up a number of dirs
up() {
	if [[ $# < 1 ]] ; then
		cd ..
	else
		CDSTR=""
		for i in {1..$1} ; do
			CDSTR="../$CDSTR"
		done
		cd $CDSTR
	fi
}

# Switch directory & ls
cl() {
	builtin cd $1
	ls --almost-all --group-directories-first --file-type
}

# FILES

alias f='noglob fd --hidden --no-ignore-vcs'
#alias f='find -not -path "*.sync*" -and -not \( -name daten -prune \)'
#alias f1='find -mindepth 1 -maxdepth 1'

which perl-rename >/dev/null && alias lowercase='perl-rename "y/A-Z/a-z/"' || alias lowercase='rename "y/A-Z/a-z/"'

mkcd() {
	mkdir -p "$1" && cd "$1"
}

# mv with automatic sudo if neccessary
smv() {
	test -w "$1" && test -w "$(dirname $2)" && mv "$@" || sudo mv "$@"
}

# Rename the file, keep it in its directory
mvf() {
	smv "$1" "$(dirname $1)/$2"
}

# Moves from $1 to $2 and replaces the original with a relative symlink
mvln() {
	file=$(test -f "$1" && echo 1 || echo 0)
	if test -d $1; then
		mkdir -p "$2"
		mv -T $1 $2
	else
		mv -v $1 $2
	fi
	[ $file -gt 0 -a -d $2 ] && 2="$2/$(basename $1)"
	ln -vsr "$2" "$1"
}

# OTHER

pathadd() {
	local IFS=":"
	local result="$@"
	unset IFS
	cat /etc/environment | head -1 | cut -d'"' -f2 | tr ":" "\n" | while read v; do
		[[ " $@ " =~ " $v " ]] || result+=":$v"
	done
	echo PATH=\"${result}\"\\n$(cat /etc/environment | tail -n +2) | sudo tee /etc/environment
}

writecompletion() {
	echo "#compdef $1" > "_$1"
	$EDITOR "_$1"
}

resetdocker() {
	#aptremove docker-ce
	kill $(ps -e | grep docker | cut -d' ' -f2)
	sudo rm -rf /var/run/docker /var/lib/docker
	sudo rm /var/run/docker.*
	#aptinstall docker-ce
}

# RANDOM

typeset -A _clean_map
if test "$BASH_VERSION"
then _clean_map=([c]=$XDG_CACHE_HOME [t]=/var/tmp)
else _clean_map=(c $XDG_CACHE_HOME t /var/tmp)
fi
_clean_folders=()
clean() {
	for f in $_clean_folders
	do test -d $f && rm -rv $f
	done

	highlight "g to clean gradle"
	if [[ $1 =~ "g" ]]; then
		find ${GRADLE_USER_HOME:-$HOME/.gradle} -mindepth 1 -maxdepth 1 -type d -exec rm -r {} \; -print
		find $projects_dir -name .gradle -print -exec rm -r {} \;
	fi

	highlight "m to clean mac-files"
	if [[ $1 =~ "m" ]]; then
		find -iname '.spotlight*' -print -exec rm -r {} \;
		find -name "*.DS_Store" -delete
	fi

	if test "$BASH_VERSION"; then
		for k in "${!_clean_map[@]}"; do
			highlight "$k to delete $_clean_map[$k]"
			echo "key  : $k"
			echo "value: ${_clean_map[$k]}"
		done
	else
		for k in "${(@k)_clean_map}"; do
			highlight "$k to delete $_clean_map[$k]"
			[[ $1 =~ "$k" ]] && rm -rfv "$_clean_map[$k]"
		done
	fi

	if test -f "/var/log/apt/history.log"; then
		aptclean_cur=$(cat "/var/log/apt/history.log" | wc -l)
		test "$aptclean_cur" -gt "$aptclean_last" && aptclean && echo "Cleaned apt"
		export aptclean_last=$aptclean_cur
	fi

	highlight "e to delete empty folders"
	[[ $1 =~ "e" ]] && find -empty -type d -delete -print
}

function zipdiff() {
	diff -W200 -y <(unzip -vql $1 | sort -k8) <(unzip -vql $2 | sort -k8) #--suppress-common-lines
}

# PROJECTS

pdiff() {
	diff -r $1 $2 -x .git -x .idea -x .gradle
}

genssh() {
	mkdir -p ~/.ssh
	test -f ~/.ssh/id_rsa.pub || ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa -q -N ""
	cat ~/.ssh/id_rsa.pub
	if test "$OSTYPE" = "cygwin"
	then cat ~/.ssh/id_rsa.pub>/dev/clipboard
	else xclip -sel clip 2>/dev/null < ~/.ssh/id_rsa.pub
	fi && echo "SSH Public key copied to clipboard" || return 0
}

createproject() {
	mkcd $1

	echo 'plugins {
	kotlin("jvm") version "1.3.41"
	application
	id("com.github.johnrengelman.shadow") version "5.1.0"
	id("com.github.ben-manes.versions") version "0.21.0"
}

sourceSets {
	main {
		java.srcDir("src/main")
		resources.srcDir("src/resources")
	}
	test {
		java.srcDir("src/test")
	}
}' > build.gradle.kts

}

# SWAP
alias memstat='free -h | awk '"'"'NR==2 {printf "Free memory:\t %s/%s\t(%d%)\n",$7,$2,$7*100/$2} NR==3 {if($2 != "0B") printf "Used swap:\t%s/%s\t(%d%)\n",$3,$2,$2*100/$3}'"'"

stopswap() {
	memstat
	swap_used=$(cat /proc/meminfo | grep SwapFree | awk '{print $2}')
	mem_available=$(cat /proc/meminfo | grep MemAvailable | awk '{print $2}')
	if test $swap_used = 0
	then echo "No swap is in use."
	elif test $swap_used + 100000 < $mem_available
	then echo "Freeing swap..."
		sudo swapoff -a
		sudo swapon -a
		memstat
	else
		echo "Not enough free memory!"
	fi
}