#!/bin/sh
# shellcheck disable=1090,1091

export ENV=~/.profile
umask 0022

export XDG_DATA_DIRS="$XDG_DATA_HOME/flatpak/exports/share:/var/lib/flatpak/exports/share${XDG_DATA_DIRS:+:}${XDG_DATA_DIRS:-}"


mkdir -p \
	"$XDG_CONFIG_HOME"         \
	"$XDG_CACHE_HOME/euandreh" \
	"$XDG_DATA_HOME/euandreh"  \
	"$XDG_STATE_HOME/euandreh" \
	"$XDG_LOG_HOME/euandreh"

GUIX_PROFILE="$XDG_CONFIG_HOME"/guix/current
if [ -r "$GUIX_PROFILE"/etc/profile ]; then
	. "$GUIX_PROFILE"/etc/profile
fi

path_add() {
	case ":$2:" in
		*:"$3":*)
			;;
		*)
			eval "export $1=$3\${$1:+:}\${$1:-}"
			;;
	esac
}

export XDG_DATA_DIRS="$XDG_DATA_HOME/flatpak/exports/share:/var/lib/flatpak/exports/share${XDG_DATA_DIRS:+:}${XDG_DATA_DIRS:-}"



#
#
#

export HISTSIZE=-1
export HISTFILE="$XDG_STATE_HOME/sh-history"
export SRC=~/dev
export PRIV_CONFIG="$XDG_PREFIX"/var/lib/private/tilde
export PRIV_STATEDIR=/var/lib/"$USER"
export EDITOR='vi'
export VISUAL="$EDITOR"
export PAGER='less -R'
export BROWSER='firefox'
export MAILDIR=~/Maildir
export TZ='America/Sao_Paulo'
export DICT=~/Desktop/en_US.dic

HOST="$(uname -s)/$(uname -m)"
TARGET="Linux/i386"
export HOST TARGET

export GUILE_HISTORY="$XDG_STATE_HOME/guile-history"
export GNUPGHOME="$XDG_CONFIG_HOME/gnupg"
export RLWRAP_HOME="$XDG_CACHE_HOME/rlwrap"
export LESSHISTFILE="$XDG_STATE_HOME/lesshst"
export NOTMUCH_CONFIG="$XDG_CONFIG_HOME/notmuch/default/config"
export PASSWORD_STORE_DIR="$SRC/private/password-store"
export MAILCAPS="$XDG_CONFIG_HOME/mailcaps/config"
export PYTHONSTARTUP="$XDG_CONFIG_HOME/python/pythonrc.py"
export NIX_PATH=nixpkgs="$HOME/dev/others/nixpkgs"
export JARPATH=~/.usr/var/mkg/share/java
export EXINIT='
	" set number
	set ruler
	set showmode
	set showmatch
	set extended
	set cedit=
	set filec=	
	set iclower
	set searchincr
	set tildeop
	set windowname
	set verbose
	set wraplen=80
	set autoindent

	map  :tagnext
	map  :tagprev
	map \ :w

	" Remover line break:
	" set leftright

	set sidescroll=32
	" map  :set leftright
	" toggle?

	" echo success?
	" map 	 :set autoindent
	" toggle?

	" map  y :p:.,$!copy
:q
	" map  p :read !xclip -o

	" map K wb"zye:o:!man "zp

	" map  f ::!env FZF_DEFAULT_COMMAND="git ls-files" fzf >> %
:edit
GIEdit 
:bg

	" map & wb"zye:o:!git grep "zp

	" map & wb"zye::!echo % >> %
:edit
GI:!git grep h"zpwi^X7c fzf >> 
::edit
Gf:l"zyt:hDIEdit + h"zp
:bg

	" map gb :vsplit
"zy1G:edit /tmp
G:read !git blame -- #
:
o"zpG!wc -lI:
'

HOSTNAME="$(hostname)"
export BORG_PASSCOMMAND="pass show $HOSTNAME/borg"
export BORG_REPO="suyin:borg/$HOSTNAME"
export BORG_REMOTE_PATH='borg14'

NPROC="$(nproc)"
export NPROC
GUILE_EFFECTIVE_VERSION="$(guile -c '(display (effective-version))')"
export N="$(($(nproc) * 2 + 1))"
export MAKEFLAGS="-j $N"
export GOPATH="$SRC/go"
export VGFLAGS='
	--show-error-list=yes
	--show-leak-kinds=all
	--leak-check=full
	--track-origins=yes
	--error-exitcode=1
'
VGFLAGS="$(printf '%s\n' "$VGFLAGS" | grep . | tr -d '\t' | tr '\n' ' ')"

export CC=gcc
export CCFLAGS='
	-g
	-fPIC
	-std=c99
	-Wall
	-Wextra
	-Wpedantic
	-Wundef
	-Wvla
	-Wmissing-prototypes
	-Wno-pointer-arith
	-Wno-psabi
'
CCFLAGS="$(printf '%s\n' "$CCFLAGS" | grep . | tr -d '\t' | tr '\n' ' ')"
export LLDFLAGS=''
export LDFLAGS="$LLDFLAGS -static"
export CFLAGS="$CCFLAGS"
export CCFLAGS="$CCFLAGS -Wconversion -Wdouble-promotion -Wshadow"
export YFLAGS='-Wother'
export GOCFLAGS="-I $PREFIX/lib/go -N"
export GOLDFLAGS="-L $PREFIX/lib/go"
export LEIN_SUPPRESS_USER_LEVEL_REPO_WARNINGS=1
export LEIN_HOME="$XDG_CONFIG_HOME"/leiningen
export GUILE_EFFECTIVE_VERSION
export LISP=li
export LISP_CLI_IMPL=sbcl
export GPODDER_HOME="$XDG_DATA_HOME"/gPodder
export GPODDER_DOWNLOAD_DIR="${XDG_DOWNLOAD_DIR:-$HOME/Downloads}"/gPodder

add_prefix() {
	path_add GUILE_LOAD_PATH          "$GUILE_LOAD_PATH"          "$1/share/guile/site/$GUILE_EFFECTIVE_VERSION"
	path_add GUILE_LOAD_COMPILED_PATH "$GUILE_LOAD_COMPILET_PATH" "$1/lib/guile/$GUILE_EFFECTIVE_VERSION/site-ccache"

	path_add C_INCLUDE_PATH   "$C_INCLUDE_PATH"   "$1/include"
	path_add LIBRARY_PATH     "$LIBRARY_PATH"     "$1/lib"
	path_add ADA_INCLUDE_PATH "$ADA_INCLUDE_PATH" "$1/include"
	path_add ADA_OBJECTS_PATH "$ADA_OBJECTS_PATH" "$1/lib"

	path_add NODE_PATH "$NODE_PATH" "$1/lib/node"


	path_add INFOPATH "$INFOPATH" "$1/share/info"
	path_add MANPATH  "$MANPATH"  "$1/share/man"
	path_add DICPATH  "$DICPATH"  "$1/share/hunspell"
	path_add PATH     "$PATH"     "$1/bin"
}
export PREFIX="$XDG_PREFIX/var/mkg"
add_prefix "$PREFIX"
add_prefix "$XDG_PREFIX"
add_prefix "$GOPATH"
add_prefix "$HOME/.nix-profile"

for d in "$XDG_PREFIX"/opt/bin-dirs/*; do
	path_add PATH "$PATH" "$d"
done

PATH="/run/setuid-programs:/run/wrappers/bin:$XDG_PREFIX/bin:$HOME/.local/bin:$PREFIX/bin:$PATH"



#
# Aliases
#

unalias -a

alias o='open'
alias mm='msmtp-queue -r'
alias s='vcs status'
alias d='vcs diff'
alias ds='vcs diff -- --staged'
alias tpd='cd "$(mkdtemp)"'
alias cls='tmux send-keys -R \; clear-history'
alias c='clean'

alias l='ls -lahiF --color'
alias grep='grep --color=auto'
alias diff='diff --color=auto'
alias watch='watch --color '
alias man='MANWIDTH=$((COLUMNS > 80 ? 80 : COLUMNS)) man'
alias less='less -R'
alias tree='tree -F -aC -I .git -I .pijul -I vendor -I STUFF -I refers'
alias make='make -e --no-print-directory'
alias mv='mv -i'
alias bc='bc -lq'
alias gdb='gdb -q --ex "set confirm off"'
alias ffmpeg='ffmpeg -loglevel warning -hide_banner'

alias sqlite='rlwrap sqlite3'
alias li='rlwrap li'
alias guile='guile -l "$XDG_CONFIG_HOME"/guile/init.scm'
alias info='info --init-file "$XDG_CONFIG_HOME"/info/infokey'
alias wget='wget --hsts-file="$XDG_STATE_HOME"/wget-hsts'
alias tmux='tmux -f "$XDG_CONFIG_HOME"/tmux/tmux.conf'

alias flush='sync && echo 3 | sudo tee /proc/sys/vm/drop_caches > /dev/null'
alias kal='khal calendar today `LANG=en.UTF-8 date +%A`'
alias tg='TG_API_ID="$(pass show tg/api_id)" TG_API_HASH="$(pass show tg/api_hash)" tg'



#
# PS1
#

error_marker() {
	STATUS=$?
	if [ "$STATUS" != 0 ]; then
		color -c redb " (!! $STATUS !!) "
	fi
}

shell_status_level() {
	if [ -z "${SHLVL:-}" ]; then
		return
	fi

	if [ "$SHLVL" = 1 ]; then
		return
	fi

	color -c white "$SHLVL"
	if [ -n "${RANGER_LEVEL:-}" ]; then
		color -c white '|'
		color -c bluei 'r'
	fi
}

shell_status_jobs() {
	JOBS="$(jobs | grep -cv autojump)"
	if [ "$JOBS" != 0 ]; then
		color -c red "$JOBS"
	fi
}

shell_status() {
	LEVEL="$(shell_status_level)"
	JOBS="$(shell_status_jobs)"

	if [ -z "$LEVEL" ] && [ -z "$JOBS" ]; then
		return
	fi

	color -c white '['
	printf '%s' "$LEVEL"
	if [ -n "$LEVEL" ] && [ -n "$JOBS" ]; then
		color -c white '|'
	fi
	printf '%s' "$JOBS"
	color -c white ']'
	printf ' '
}

timestamp_fn() {
	color -c blacki '\T'
}

path() {
	color -c yellowb '\w/'
}

guix_env() {
	if [ -z "${GUIX_ENVIRONMENT:-}" ]; then
		return
	fi

	printf '\n'
	color -c blacki '~> '
	color -c purple 'guix environment '
	printf '('
	color -c blueb "$GUIX_ENVIRONMENT"
	printf ')'
}

in_nix_shell() {
	if [ -z "${IN_NIX_SHELL:-}" ]; then
		return
	fi

	printf '\n'
	color -c blacki '~> '
	color -c purpleb "$IN_NIX_SHELL "
	color -c purple 'nix-shell '
	printf '('
	color -c blueb "${name:-}"
	printf ')'
}

in_ssh_session() {
	if [ -n "${SSH_CLIENT:-}" ]; then
		color -c blackb '\\u'
		printf '@'
		color -c purple '\\H'
	fi
}

direnv_status() {
	if [ -n "${DIRENV_FILE:-}" ]; then
		color -c lightblue '.'
	fi
}

makeflags_status() {
	if [ -n "${MAKEFLAGS:-}" ]; then
		color -c lightblue '|'
	fi
}

VCS_PS1_TIMEOUT=0.5
vcs_status() {
	timeout "$VCS_PS1_TIMEOUT" vcs ps1 || if [ $? = 124 ]; then
		color -c red '❌'
	fi
}

PS1='`error_marker`'$(timestamp_fn)' '$(path)'`direnv_status``makeflags_status` `shell_status``vcs_status``guix_env``in_nix_shell`
'$(in_ssh_session)'$ '
export PS1

bind 'set show-mode-in-prompt on'
bind 'set vi-ins-mode-string \1\e[34;1m\2.\1\e[0m\2'
bind 'set vi-cmd-mode-string \1\e[35;1m\2^\1\e[0m\2'
set -o vi
set -o emacs



g() {
	if [ -z "${1:-}" ]; then
		cat <<-'EOF'
			Missing PATTERN.

			Usage:
			  g PATTERN [FILE]
		EOF
		return 2
	fi
	PAT="$(mkstemp)-g-shell-function"
	printf '%s' "$1" > "$PAT"
	PREVIEW_CMD="highlight -n{2} -f{1} -e \"\$(cat '$PAT')\""

	LINE="$(
		# shellcheck disable=2086
		git grep -iIE --color=always -n -- "$(cat "$PAT")" ${2:-} |
			fzf \
				--exit-0                           \
				--select-1                         \
				--ansi                             \
				--delimiter=:                      \
				--preview-window 'up,60%,+{2}+3/3' \
				--preview "$PREVIEW_CMD"
	)"
	rm -f "$(dirname "$PAT")"/*-g-shell-function
	if [ -n "$LINE" ]; then
		FILE="$(  printf '%s\n' "$LINE" | cut -d: -f1)"
		NUMBER="$(printf '%s\n' "$LINE" | cut -d: -f2)"
		case "$1" in
			"'"*"'")
				# Best effort handling of string escaping, since
				# one can't recover what was typed at this level
				H="\"$1\""
				;;
			*)
				H="'$1'"
				;;
		esac
		if [ -z "${2:-}" ]; then
			history -s g "$H"
		else
			history -s g "$H" "'$2'"
		fi
		history -s "$VISUAL" +"$NUMBER" "'$FILE'"
		"$VISUAL" +"$NUMBER" "$FILE"
	fi
}

f() {
	P="f-shell-function$(pwd | sed 's|/|-|g')"
	F="$(
		vcs ls |
			grep -E -e "${2:-.}" |
			remembering -p "$P" -- \
				fzf  \
					--select-1          \
					--exit-0            \
					--preview-window up \
					--preview 'cat {}'
	)"
	CMD="${1:-$VISUAL}"
	if [ -n "$F" ]; then
		if [ -z "${1:-}" ]; then
			history -s f
		elif [ -z "${2:-}" ]; then
			history -s f "$1"
		else
			history -s f "$1" "'$2'"
		fi

		case "$F" in
			-*)
				DELIM='--'
				;;
			*)
				DELIM=''
				;;
		esac
		history -s "$CMD" $DELIM "'$F'"

		"$CMD" -- "$F"
	fi
}

idiff() {
	diff -U10 --color=always "$1" "$2" | ifne less -R
}



r() {
	. ~/.profile
}

rr() {
	r
	direnv allow
}

_edit_without_executing() {
	F="$(mkstemp)"
	printf '%s\n' "$READLINE_LINE" > "$F"
	e "$F"
	READLINE_LINE="$(cat "$F")"
	READLINE_POINT="${#READLINE_LINE}"
	rm -f "$F"
}
if set -o | grep 'on' | grep -Eq '^(vi|emacs)'; then
	bind -x '"\C-x\C-e":_edit_without_executing'
fi




#
# GPG and SSH agents configuration
#

SSH_AUTH_SOCK=$(gpgconf --list-dirs agent-ssh-socket)
GPG_TTY=$(tty ||:)
export GPG_TTY SSH_AUTH_SOCK
gpgconf --launch gpg-agent



case $- in
	*i*)
		stty -ixon  # Disable C-s/C-q mode
		;;
	*)
		;;
esac

F="$PRIV_CONFIG"/privrc.sh
if [ -r "$F"  ]; then
	# Extra rc code to be loaded, stored in private repository
	. "$F"
fi


#
# Only for graphical sessions
#

if [ -n "${DISPLAY:-}" ]; then
	xset s 1800
	xset r rate 225 100
	# Get keycode number by running `xev(1)`, and symname by looking at the
	# definitions in `X11/keysymdef.h`.
	xmodmap \
		-e 'keycode 118 = ssharp bar'

fi

#
# From here on, bash-specific things.
#

if [ -z "$BASH_VERSION" ]; then
	return
fi

# shellcheck disable=3045
ulimit -c unlimited

export INPUTRC="$XDG_CONFIG_HOME/bash/inputrc"
export HISTCONTROL=ignorespace:ignoredups

eval "$(direnv hook bash)"


#
# From here on, interactive-only bash-specific things.
#

case $- in
	*i*)
		;;
	*)
		return
		;;
esac

HOME_ENVIRONMENT="$HOME"/.guix-home

# IIRC, the Guix profile should do this
alias have='true'
for f in "$HOME_ENVIRONMENT"/profile/etc/bash_completion.d/*; do
	. "$f"
done
unalias have

# IIRC, the Guix package should do this
F="$HOME_ENVIRONMENT"/profile/share/autojump/autojump.bash
if [ -r "$F" ]; then
	. "$F"
fi

unset HOME_ENVIRONMENT
export TD_USE_BUILTIN_HOOKS='git'
