export PATH=$CONFIG_DIR/mybin:$PATH
export TERM="xterm-color"
export NIXPKGS_ALLOW_UNFREE=1

# needed to make ssh -X work
# see: https://unix.stackexchange.com/questions/412065/ssh-connection-x11-connection-rejected-because-of-wrong-authentication
export XAUTHORITY=$HOME/.Xauthority

cd ~

### mize aliases
alias mg="mize get"
alias mr="mize run"
alias ms="mize set"
alias md="mize run dev"
alias sci="mize run sci"

### nix build hosts
export acern="ssh://acern x86_64-linux,aarch64-linux - 20 10 big-parallel - -"
export fe="ssh://fe x86_64-linux,aarch64-linux - 20 10 big-parallel - -"
export fusu="ssh://fusu x86_64-linux,aarch64-linux - 20 10 big-parallel - -"
export mac="ssh://mac x86_64-linux,aarch64-linux - 8 5 big-parallel - -"
export mosatop="ssh://mosatop x86_64-linux,aarch64-linux - 8 5 big-parallel - -"
export hpm="ssh://hpm x86_64-linux,aarch64-linux - 8 5 big-parallel - -"

### ssh completions
_ssh_completion() {
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    # Grabs hostnames from both ssh config and known_hosts
    opts=$(awk '/^Host / && $2 !~ /[*?]/ {print $2}' $CONFIG_DIR/hosts/main/ssh_config 2>/dev/null; \
           awk '{split($1,a,","); print a[1]}' ~/.ssh/known_hosts 2>/dev/null | tr -d '[]')
    COMPREPLY=( $(compgen -W "$opts" -- "$cur") )
    return 0
}
_scp_completion() {
    local cur opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    local OLD_WORDBREAKS=$COMP_WORDBREAKS
    COMP_WORDBREAKS=${COMP_WORDBREAKS//:/}


    # 2. Generate host choices using your existing logic
    opts=$(awk '/^Host / && $2 !~ /[*?]/ {print $2}' $CONFIG_DIR/hosts/main/ssh_config 2>/dev/null; \
           awk '{split($1,a,","); print a[1]}' ~/.ssh/known_hosts 2>/dev/null | tr -d '[]')
           

    # 3. Combine both hosts and local files into the initial completion pool
    # This allows typing 'sc[TAB]' to see both local files and your SSH hosts.
    COMPREPLY=( $(compgen -S ":" -W "$opts" -- "$cur") $(compgen -f -- "$cur") )

    # Enable filename formatting so local directory trailing slashes work
    compopt -o filenames 2>/dev/null
    return 0

}
complete -F _ssh_completion ssh sftp
complete -F _scp_completion -o nospace scp


# my prompt
if [[ "main" == "main" ]]
then
	#export PS1="\[\033[01;34m\]\W\[\033[00m\]\[\033[01;32m\]\[\033[00m\] ❯❯❯ "
	#export PS1="\[\033[01;34m\]\W\[\033[00m\]\[\033[01;32m\]\[\033[00m\] > "
  # \n\[\033[1;34m\][\[\e]0;\u@\h: \w\a\]\u@\h:\w]\$\[\033[0m\]
  #export PS1="\W > ";

  export PS1="cachy \[\033[01;34m\]\W\033[00m ❯❯❯ "
else
	#export PS1="\033[1;32mmain❯ \[\033[01;34m\]\W\[\033[00m\]\[\033[01;32m\]\[\033[00m\] ❯❯❯ "

  export PS1="\033[1;32mmain\[\033[01;34m\] \W\033[00m ❯❯❯ "
fi


# function to create a tmpdir, to use for some temporary work....
# made this, to not just keep cluttering my $HOME... with all kinds of projects
function mt () {
  export TOPDIR=$HOME/tmp
  mkdir -p $TOPDIR
  cd $(python $CONFIG_DIR/scripts/quick-tmp-dir.py "$@")
}




# so that programms i spawn from my shell don't have so high cpu priority
[ which renice 2>/dev/null ] && renice -n 9 $$ > /dev/null



# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# making reverse search "going back" work with strg+s
stty -ixon


			#################### functions ####################

# nix shell with
nrepl(){
  nix repl --expr "rec { nixpkgs = builtins.getFlake \"nixpkgs/$NIXPKGS_REV\"; pkgs = import nixpkgs {}; flake = builtins.getFlake \"git+file://$(pwd)\"; config = builtins.getFlake \"git+file://$CONFIG_DIR\"; } $@"
}

# A shortcut function that simplifies usage of xclip.
# - Accepts input from either stdin (pipe), or params.
# ------------------------------------------------
cb() {
  local _scs_col="\e[0;32m"; local _wrn_col='\e[1;31m'; local _trn_col='\e[0;33m'

  # Check user is not root (root doesn't have access to user xorg server)
  if [[ "$USER" == "root" ]]; then
	 echo -e "$_wrn_col""Must be regular user (not root) to copy a file to the clipboard.\e[0m"
  else
	 # If no tty, data should be available on stdin
	 if ! [[ "$( tty )" == /dev/* ]]; then
		input="$(< /dev/stdin)"
	 # Else, fetch input from params
	 else
		input="$*"
	 fi
	 if [ -z "$input" ]; then  # If no input, print usage message.
		echo "Copies a string to the clipboard."
		echo "Usage: cb <string>"
		echo "       echo <string> | cb"
	 else
		# Copy input to clipboard
		echo -n "$input" | wl-copy
		# Truncate text for status
		if [ ${#input} -gt 80 ]; then input="$(echo $input | cut -c1-80)$_trn_col...\e[0m"; fi
		# Print status.
		echo -e "$_scs_col""Copied to clipboard:\e[0m $input"
	 fi
  fi
}

# git commit func
    function gc(){
      tmp=$(echo -en $@)
      git commit -m "$tmp"
    }


	# while true -> do cat.....
	function follow (){
	while true;
	do 
		cat $@;
	done
	}


	# little looping func
	function loop (){
	if [ "$1" == "-s" ]
	then
		for (( i=1; i<=$3; i++ )); do sleep $2; ${@:4}; done
		return
	fi
	case $1 in
		 ''|*[!0-9]*) 
			# infinit iterations
			while true; do $@; done
			return
		 ;;
		 *) ;;
	esac
	for (( i=1; i<=$1; i++ ));do ${@:2}; done
	}


	function psk(){
		ps -e | grep $1 | awk '{print $1}' | xargs kill
	}


	sd() {
		if [ "$1" == "" ]
		then
			sudo -E $(history | tail -n 2 | head -n 1 | awk '{$1=""; print $0}')
		else
			sudo -E $@
		fi
	}


	# rech
	function rech(){
	python3 -c "from math import *; print($@)"
	}


	# cf - copy file
	function cf() { cat "$1" | cb; }


	# shorter zathura
	function zath(){
	zathura "$@" 2>/dev/null &
	}

	#################### completions ####################
	complete -cf sudo
	complete -cf sd
	complete -W "start stop restart status daemon-reload" stl

	# ru
	complete -W "mnt-wechner sync-school wstunnel hibernate p speed-test-nixos-iso speed-test-upload speed-test-download bat bstat mnt-files-local mnt-lan-local mnt-files-remote mnt-lan-remote suspend rm-tab-cur rm-last-char mnt-school mnt-host davinci-resolve-convert-videos" ru


		

# function to open remote desktops of my hosts
complete -W "mosatop acern phone mwin win fwin ki mac mandroid" rp
function rp () {
  host=$1

  if [[ "$host" == "mosatop" ]]
  then
    xfreerdp3 /u:"c2vi" /v:mosatop /p:$(cat $SECRETS_DIR/mosatop-rdp-password) /dynamic-resolution +clipboard +auto-reconnect /wm-class:"Microsoft Windows"

  elif [[ "$host" == "acern" ]]
  then
    xfreerdp3 /u:"seb" /v:acern /p:$(cat $SECRETS_DIR/acern-rdp-password) /dynamic-resolution +clipboard +auto-reconnect /wm-class:"Microsoft Windows"

  elif [[ "$host" == "mwin" ]]
  then
    xfreerdp3 /u:"me" /v:mac:4400 /p:$(cat $SECRETS_DIR/win-vm-pwd) /dynamic-resolution +clipboard +auto-reconnect +home-drive /wm-class:"Microsoft Windows";

  elif [[ "$host" == "win" ]]
  then
    xfreerdp3 /u:"me" /v:192.168.122.141 /p:$(cat $SECRETS_DIR/win-vm-pwd) /dynamic-resolution +clipboard +auto-reconnect +home-drive /wm-class:"Microsoft Windows";

  elif [[ "$host" == "phone" ]]
  then
    ssh phone "source ~/.bashrc && on" &
    rustdesk --connect 100.88.245.227

  elif [[ "$host" == "vnc-fwin" ]]
  then
    remmina -c $DATA_DIR/remmina/fwin.remmina

  elif [[ "$host" == "fwin" ]]
  then
    xfreerdp3 /u:"me" /v:fusu:9002 /p:$(cat $SECRETS_DIR/win-vm-pwd) /dynamic-resolution +clipboard +auto-reconnect +home-drive /wm-class:"Microsoft Windows";

  elif [[ "$host" == "ki" ]]
  then
    remmina -c $DATA_DIR/remmina/ki.remmina

  elif [[ "$host" == "mac" ]]
  then
    remmina -c $DATA_DIR/remmina/mac.remmina

  elif [[ "$host" == "mandroid" ]]
  then
    remmina -c $DATA_DIR/remmina/mandroid.remmina

  fi
}


HISTCONTROL=ignoredups
HISTFILE="$DATA_DIR/$HOSTNAME/bash-history"
HISTFILESIZE=10000000
HISTIGNORE=ls:cd:exit
HISTSIZE=10000
mkdir -p "$(dirname "$HISTFILE")"

shopt -s histappend
shopt -s checkwinsize
shopt -s globstar

# aliases
alias bl=bluetoothctl
alias oebb=~/work/src/oebb/oebb.sh
alias hl=hyprctl
alias ls='ls --color=auto'
alias archive-video='yt-dlp -f "bv*+ba/b" --merge-output-format mp4 --embed-thumbnail --write-thumbnail --convert-thumbnails png --add-metadata -o "%(title)s.%(ext)s"'
alias c='cd ..'
alias cbs='history | tail -n 2 | head -n 1 | awk '\''{$1=""; print $0}'\'' | cut -c 2- | cb'
alias gitlog='git log --all --graph'
alias gs='git status'
alias ipa='				echo -e "IPv4:\n-----------------"
				ip -o a show | cut -d " " -f 2,7 | grep -v : | column -t
				echo -e "\nIPv6:\n-----------------"
				ip -o a show | cut -d " " -f 2,7 | grep : | column -t
			'
alias kwoche='curl -k https://kalenderwoche.celll.net/?api=1; echo'
alias ports='/nix/store/8a1gk78021ashna4c2hmk8xxwb1pkwwm-lsof-4.99.4/bin/lsof -i -P -n'
alias psg='ps -e | grep'
alias shutdown='echo try harder.... xD'
alias sl=ls
alias stl='sudo systemctl'
alias u='sudo umount ~/mnt'
alias vim=nvim
alias virsh='virsh -c qemu:///system'

eval "$(direnv hook bash)"
