#!/bin/bash

#
# ▒█▀▀▀ ▒█▀▀█ 	Filip Rojek
# ▒█▀▀▀ ▒█▄▄▀ 	http://git.filiprojek.cz/fr/
# ▒█░░░ ▒█░▒█ 	http://filiprojek.cz/
#

# .bashrc
source /etc/profile

# If not running interactively, don't do anything
[[ $- != *i* ]] && return


# PS1 shell color
## simple white ps1 without git
#PS1='\[\e[0m\][\[\e[0m\]\u\[\e[0m\]@\[\e[0m\]\H \[\e[0m\]\W\[\e[0m\]]\[\e[0m\]\$ \[\e[0m\]'

## based on: https://www.cyberciti.biz/faq/bash-shell-change-the-color-of-my-shell-prompt-under-linux-or-unix/
## get current branch in git repo
function parse_git_branch() {
	BRANCH=`git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'`
	if [ ! "${BRANCH}" == "" ]
	then
		STAT=`parse_git_dirty`
		echo "[${BRANCH}${STAT}]"
	else
		echo ""
	fi
}

## get current status of git repo
function parse_git_dirty { status=`git status 2>&1 | tee`
	dirty=`echo -n "${status}" 2> /dev/null | grep "modified:" &> /dev/null; echo "$?"`
	untracked=`echo -n "${status}" 2> /dev/null | grep "Untracked files" &> /dev/null; echo "$?"`
	ahead=`echo -n "${status}" 2> /dev/null | grep "Your branch is ahead of" &> /dev/null; echo "$?"`
	newfile=`echo -n "${status}" 2> /dev/null | grep "new file:" &> /dev/null; echo "$?"`
	renamed=`echo -n "${status}" 2> /dev/null | grep "renamed:" &> /dev/null; echo "$?"`
	deleted=`echo -n "${status}" 2> /dev/null | grep "deleted:" &> /dev/null; echo "$?"`
	bits=''
	if [ "${renamed}" == "0" ]; then
		bits=">${bits}"
	fi
	if [ "${ahead}" == "0" ]; then
		bits="*${bits}"
	fi
	if [ "${newfile}" == "0" ]; then
		bits="+${bits}"
	fi
	if [ "${untracked}" == "0" ]; then
		bits="?${bits}"
	fi
	if [ "${deleted}" == "0" ]; then
		bits="x${bits}"
	fi
	if [ "${dirty}" == "0" ]; then
		bits="!${bits}"
	fi
	if [ ! "${bits}" == "" ]; then
		echo " ${bits}"
	else
		echo ""
	fi
}

export PS1="\[\e[36m\][\[\e[m\]\[\e[36m\]\u\[\e[m\]\[\e[36m\]@\[\e[m\]\[\e[36m\]\h\[\e[m\]\[\e[36m\] \[\e[m\]\[\e[36m\]\W\[\e[m\]\[\e[36m\]]\[\e[m\]\[\e[32;40m\]\`parse_git_branch\`\[\e[m\]\[\e[36m\]\\$\[\e[m\] "


# Functions
function convertm() {
  for f in *.jpg; do
    convert ./"$f" ./"${f%.}.pdf"
  done
}

## Create new directory and descend into it
function mkcd() { mkdir -p "$@" && cd "$@"; }

## Kill all that use port
killport () {
  kill $(lsof -t -i:"$1")
}

## Enable runit service (for Void Linux)
function sv-enable () {
  if test -e /etc/sv/$1; then
    doas ln -sv /etc/sv/$1 /var/service/
  else
    echo "Error: /etc/sv/$1 does not exist"
  fi
}

## Switch keyboard layouts
function xkb-switch () {
	LAYOUT=$(setxkbmap -query | grep layout | awk '{print $2}')
	if [[ $LAYOUT == "us" ]]; then
	  setxkbmap cz qwerty
	else
	  setxkbmap us
	fi
}

## Repeat command until exit
function dorepeat() {
	while true; do
		"$@"
		sleep 1
		echo
	done
}

## Generate random password (default length is 16 chars)
function genpasswd() {
	local l=$1
	[ -n "$l" ] || l=16
	tr -dc A-Za-z0-9_ < /dev/urandom \
		| head -c "$l" | xargs
}

## Download m3u8 stream
m3u8-download() {
  yt-dlp --list-formats "$1"
  echo "enter format code:"
  read format_code
  yt-dlp -f $format_code --hls-prefer-native "$1"
}

md2pdf() {
    if [[ -z "$1" ]]; then
        echo "Usage: md2pdf input.md [output.pdf]"
        return 1
    fi

    local input="$1"
    local output="${2:-${input%.*}.pdf}"

    # Adding -V mainfont resolves the empty font fallback error
    pandoc "$input" -o "$output" --pdf-engine=typst -V mainfont="DejaVu Sans"
}

typstwatch() {
    if [[ -z "$1" ]]; then
        echo "Usage: tw <filename>"
        return 1
    fi

    # Strip extension if provided and use the base name
    local base="${1%.*}"

    (zathura "${base}.pdf" &) && typst watch "${base}.typ"
}

## GPG functions
gpg_encrypt () {
	output=~/"${1}".$(date +%s).enc
	#gpg --encrypt --armor --output ${output} -r 0x0000 -r 0x0001 -r 0x0002 "${1}" && echo "${1} -> ${output}"
	gpg --encrypt --armor --output ${output} "${1}" && echo "${1} -> ${output}"
}

gpg_decrypt () {
	output=$(echo "${1}" | rev | cut -c16- | rev)
	gpg --decrypt --output ${output} "${1}" && echo "${1} -> ${output}"
}

# for spawning new terminal instances in the current working directory in foot terminal
osc7_cwd() {
    local strlen=${#PWD}
    local encoded=""
    local pos c o
    for (( pos=0; pos<strlen; pos++ )); do
        c=${PWD:$pos:1}
        case "$c" in
            [-/:_.!\'\(\)~[:alnum:]] ) o="${c}" ;;
            * ) printf -v o '%%%02X' "'${c}" ;;
        esac
        encoded+="${o}"
    done
    printf '\e]7;file://%s%s\e\\' "${HOSTNAME}" "${encoded}"
}
PROMPT_COMMAND=${PROMPT_COMMAND:+${PROMPT_COMMAND%;}; }osc7_cwd


# Aliases and Exports
## utility
alias cal="cal -m"

## shell
#set -o vi # vim keybinding in terminal
EDITOR=vim # prefered editor
stty -ixon # reverse i search bash 
complete -cf doas # doas completion
alias ls="ls --color=auto"
alias ll="ls -lFh"
alias la="ls -alh"
alias l="ls -CF"
#alias ld="ls -d -F */"
alias lda="ls -l -d -p */"
alias tree="tree -C"
export HISTCONTROL=ignoredups # fuckin history identical vole

## network

## shortcuts
alias lgfr="cd ~/git/fr/"
alias lgfw="cd ~/git/fofrweb/"
alias lbc="cd ~/git/fr/pedf/bc"

## programs
#alias r="ranger"
alias r="yazi"
alias feh="feh --scale-down"
#alias dragon="dragon-drop"
alias xclip="xclip -selection c"
alias grep='grep --color=auto'
alias passmenu="passmenu -l 10"
alias speedtest="speedtest-cli"
alias "cd.."="cd .."
alias df='df -h'                          # human-readable sizes
alias free='free -m'                      # show sizes in MB
#alias tldr='tldr -t base16'               # colors

## gpg encryption
# verify signature for isos
alias gpg-check="gpg2 --keyserver-options auto-key-retrieve --verify"
# receive the key of a developer
alias gpg-retrieve="gpg2 --keyserver-options auto-key-retrieve --receive-keys"

## confirm before overwriting something
alias cp="cp -i"
alias mv='mv -i'
alias rm='rm -i'

## downloaders
alias uloztodl="ulozto-downloader --auto-captcha --parts 40"
alias wgetall="wget -r --no-parent"
### yt-dlp
alias yta-aac="yt-dlp --extract-audio --audio-format aac "
alias yta-best="yt-dlp --extract-audio --audio-format best "
alias yta-flac="yt-dlp --extract-audio --audio-format flac " 
alias yta-m4a="yt-dlp --extract-audio --audio-format m4a "
alias yta-mp3="yt-dlp --extract-audio --audio-format mp3 "
alias yta-opus="yt-dlp --extract-audio --audio-format opus "
alias yta-vorbis="yt-dlp --extract-audio --audio-format vorbis "
alias yta-wav="yt-dlp --extract-audio --audio-format wav "
alias ytv-best="yt-dlp -f bestvideo+bestaudio "

## short scripts
alias wttr="curl -s wttr.in/Prague?q0M"
alias wttrfull="curl -s wttr.in/Prague?qM"
alias whatsmyip="dig +short myip.opendns.com @resolver1.opendns.com"
alias htmlvlna="vlna -s -r -x 266E6273703B"
alias fuck='doas $(history -p \!\!)'
alias sudo="doas"
alias treecat="tail -n +1 **/*"

## void xbps aliases
#alias xi="doas xbps-install"
alias xi="doas xi"
alias xq="xbps-query -Rs"
alias xr="doas xbps-remove"
alias xrd="doas xbps-remove -R" # remove all dependencies
alias xu="doas xbps-install -Suv" # update
alias xreinstall="doas xbps-install -f"
alias xlu="xbps-install -Suvn" # list packages requiring updates

## random
alias todo="vim ~/_todo.md"
alias schm="~/.screenlayout/home.sh"
alias sclp="~/.screenlayout/laptop.sh"

### bare git repo alias for dotfiles
alias config="/usr/bin/git --git-dir=$HOME/.dotfiles --work-tree=$HOME"

# Exports
export PATH="$PATH:$HOME/.cargo/bin"
export PATH="$PATH:$HOME/.local/bin"
export PATH="$PATH:/var/lib/flatpak/exports/bin"
export PATH="$PATH:$HOME/.local/share/flatpak/exports/bin"
export PATH="$PATH:/home/fr/git/microlab/wpa_tui/dmenu_scripts"
export PATH="$PATH:$HOME/.local/bin/flutter/bin"
export PATH="$PATH:$HOME/.local/bin/cmdline-tools/bin"
export PATH="$PATH:$HOME/.config/emacs/bin"

export ANDROID_SDK_ROOT="$HOME/.local/android-sdk"
export ANDROID_HOME="$HOME/.local/android-sdk"
export PATH="$ANDROID_SDK_ROOT/platform-tools:$PATH"
export PATH="$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$PATH"


# Locales Exports
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8

# autologin on tty1
# if [ -z "$DISPLAY" ] && [ "$(fgconsole)" -eq 1 ]; then
# 	exec startx
# fi

