#
# ~/.bashrc :: by frode klevstul
#


# ---
# special stuff
# ---

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

# https://github.com/gsamokovarov/jump
eval "$(jump shell --bind=j)"

# https://github.com/ajeetdsouza/zoxide
eval "$(zoxide init bash)"

# ---
# environment variables
# ---
# see `dots/environment/environment`


# ---
# miscellaneous aliases
# ---

alias azurevpnclient="/opt/microsoft/microsoft-azurevpnclient/microsoft-azurevpnclient"
alias biggestfiles="find ~ -type f -exec du -h {} + 2>/dev/null | sort -hr | head -n 20"
alias cp="cp -i"                            # confirm before overwriting something
alias ct="sudo ct"
alias decrypt="gpg --decrypt"
alias df='df -h'                            # human-readable sizes
alias diskusage="ncdu -x"
alias dragon="dragon-drop --and-exit --all --print-path"
alias du="du --summarize --human-readable"
alias dus="du --summarize --human-readable * | sort -h"
alias encrypt="gpg --encrypt --sign --recipient frode@klevstul.com"
alias extract="extract.sh"
alias gparted="sudo gparted"
alias grep='grep --color=auto'
alias hyprRld="hyprctl reload"
alias hyprUpd="ct d h && hyprRld"
alias ipadr='ip -br a'
alias ipcam="ffplay rtsp://192.168.31.220:554/1"
alias ipify='http https://api.ipify.org?format=json'
alias journal='journalctl --since "1 hour ago"'
alias keyringreset="trash-put /home/poq/.local/share/keyrings/*.keyrings"
alias ls='ls --color=auto'
alias myip="echo $(wget http://ipinfo.io/ip -qO -)"
alias neofetch='fastfetch'
alias quantumfix="pw-metadata -n settings 0 clock.force-quantum 1024"
alias sb="unalias -a; source ~/.bashrc"
alias sbr="unalias -a; source /home/poq/syncDir/repos/git/gi.op.fo/lnx-arch/dots/bash/.bashrc"   # source bash (from) repo
alias sizeInBytes="stat -c %s"
alias ssh_weba_r="ssh -v -t root@weba -p 1808 'export TERM=xterm; cd /tmp; bash -l'" # 'weba' is configured in 'dots/ssh/config'
alias ssh_weba_u="ssh -v -t usr@weba -p 1808 'export TERM=xterm; cd /tmp; bash -l'"
alias ssh="ssh -v"
alias tp-empty="trash-empty && gio trash --empty"
alias tp-list="tree ~/.local/share/Trash/"
alias tp-restore="trash-restore"
alias tp="tp.sh"
alias trash-empty="trash-empty && gio trash --empty"
alias tree="tree --du -h"

# app images
alias pgmodeler2="/home/poq/syncDir/swas/portableApps/pgmodeler_plus-2*"
alias pgmodeler="/home/poq/syncDir/swas/portableApps/pgmodeler_plus-1*"


# ---
# terminal
# ---

# x terminal shell start string | https://askubuntu.com/questions/1340319/ps1-string-full-documentation-and-reference-page
# https://bash-prompt-generator.org/
# https://askubuntu.com/questions/193416/adding-timestamps-to-terminal-prompts
PS1='\n⚙[\D{%y%m%d%H%M}|\u@\h|\w]\$ '
#PS1='\[\e[01;32m\]\u@\h \[\e[01;34m\]\w\[\e[00m\]\$ '

# change the window title of x terminals
case ${TERM} in
    xterm*|rxvt*|Eterm*|aterm|kterm|gnome*|interix|konsole*)
        PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/\~}\007"'
        ;;
    screen*)
        PROMPT_COMMAND='echo -ne "\033_${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/\~}\033\\"'
        ;;
esac


# ---
# lf & superfile
# ---

# lf (change directory on quit)
# ---
lf() {
    local tmp=$(mktemp)
    command foot lf -last-dir-path="$tmp" "$@" &>/dev/null &
    if [[ -f "$tmp" ]]; then
        local dir=$(cat "$tmp")
        rm -f "$tmp"
        if [[ -d "$dir" && "$dir" != "$(pwd)" ]]; then
            cd "$dir"
        fi
    fi
}

# superfile (change directory on quit)
# ---
spf() {
    os=$(uname -s)

    # Linux
    if [[ "$os" == "Linux" ]]; then
        export SPF_LAST_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/superfile/lastdir"
    fi

    command spf "$@"

    [ ! -f "$SPF_LAST_DIR" ] || {
        . "$SPF_LAST_DIR"
        rm -f -- "$SPF_LAST_DIR" > /dev/null
    }
}


# ---
# misc
# ---

# recursively zip everything in current directory, name the zip file $1, and exclude (-x) itself from the zip process
zipr() {
    zip -r $1 . -x $1
}

#gpxImporter() {
#    cd /home/poq/syncDir/repos/git/gi.op.fo/gpx-importer/go/src/
#    go run main.go
#    cd -
#}

generate_password() {
  local length=30
  local chars='A-Za-z0-9!@#$%^&*()_+[]{}|;:,.<>?'
  tr -dc "$chars" < /dev/urandom | head -c $length
  echo
}

randoms() {
    echo "----------"

    ranwrd1=$(shuf -n 1 /usr/share/dict/cracklib-small)
    ranwrd1="${ranwrd1//[^[:alpha:]]/}"
    ranwrd2=$(shuf -n 1 /usr/share/dict/cracklib-small)
    ranwrd2="${ranwrd2//[^[:alpha:]]/}"
    rancmd=$(compgen -ac | shuf -n 1)
    randnum=$(( 1000 + SRANDOM % 9000 ))
    randalp=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 10)

    echo "w1: ${ranwrd1} | w2: ${ranwrd2} | c: ${rancmd} | n: ${randnum} | a: ${randalp}"

    randstr0="${randnum} ${ranwrd1} ${ranwrd2} ${rancmd}_${randalp}"
    randstr1="${randnum}_${ranwrd1}_${ranwrd2}_${rancmd}${randalp}"
    randstr2="${randnum}${ranwrd1}${ranwrd2}${rancmd//[^[:alpha:]]/}${randalp}"
    randstr3=$(generate_password)

    echo "s0: ${randstr0}"
    echo "s1: ${randstr1}"
    echo "s2: ${randstr2}"
    echo "s3: ${randstr3}"

    echo "----------"
}


# ---
# mounting
# ---

alias nas-mount="nas mount 192.168.31.77"
alias nas-umount="nas umount"

nas() {
    if [[ ! -e "/mnt/nas" ]] ; then
        sudo mkdir -p "/mnt/nas"
        sudo mkdir -p "/mnt/nas-fam"
    elif [[ ! -d "/mnt/nas" ]] || [[ ! -d "/mnt/nas-fam" ]] ; then
        echo "'/mnt/nas' and/or '/mnt/nas-fam' exist, but is not a directory" 1>&2
    fi

    if [[ -n $1 ]] ; then
        if [[ $1 == "umount" ]] || [[ $1 == "unmount" ]] ; then
            echo "umount /mnt/nas & /mnt/nas-fam"
            sudo umount -l /mnt/nas
            sudo umount -l /mnt/nas-fam
        elif [[ $1 == "mount" ]] && [[ -n $2 ]]; then
            echo "mount /mnt/nas & /mnt/nas-fam"
            sudo mount -t cifs -o credentials=/home/poq/syncDir/secrets/nas/lillesorteboks.txt,iocharset=utf8,noperm //$2/fro /mnt/nas
            sudo mount -t cifs -o credentials=/home/poq/syncDir/secrets/nas/lillesorteboks.txt,iocharset=utf8,noperm //$2/fam /mnt/nas-fam
            tree -L 2 /mnt/nas
            tree -L 2 /mnt/nas-fam
        else
            echo "missing the ip when doing a mount? or, just trying a weird command? try: 'nas {mount,umount} {ip?}'"
        fi
    else
        echo "sry, bud! try: 'nas {mount,umount} {ip?}'"
    fi
}


# ---
# multimedia
# ---

#alias videoCompressor="/home/poq/syncDir/repos/git/gi.op.fo/miniProjects/2104_videoCompressor/src/vc_v2.sh"
#alias videoWatermark="/home/poq/syncDir/repos/git/gi.op.fo/miniProjects/2104_videoCompressor/src/vcwm_v1.sh"
#alias toJpg='/home/poq/syncDir/repos/git/gi.op.fo/miniProjects/2306_toJpg/toJpg.sh'

# https://itsfoss.com/compress-pdf-linux/
pdfCompress() {
    gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.5 -dPDFSETTINGS=/ebook \
    -dNOPAUSE -dQUIET -dBATCH -sOutputFile=$1.compressed.pdf $1
}

# https://stackoverflow.com/questions/8933053/check-duration-of-audio-files-on-the-command-line
lengthInSeconds() {
    ffprobe -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 $1 2>/dev/null
}


# ---
# networking
# ---

nmrestart() {
    systemctl restart NetworkManager
    systemctl status NetworkManager
}


# ---
# rotate
# ---

# https://boulderappsco.postach.io/post/convert-decimal-to-base-36-alpha-numeric-in-bash-linux
function decimal_to_base36(){
    BASE36=($(echo {0..9} {A..Z}));
    arg1=$@;
    for i in $(bc <<< "obase=36; $arg1"); do
        echo -n ${BASE36[$(( 10#$i ))]}
    done && echo
}

# loops every 36, so that 36 becomes 1, etc
decimal_to_base36_wrap() {
    local n=$(( $1 % 36 ))
    decimal_to_base36 $n
}

rot() {
    local shift=$1
    local text=$2
    local alpha=abcdefghijklmnopqrstuvwxyz
    local n

    if [[ -z $shift || -z $text ]]; then
        echo "Usage: rot <shift> <text>"
        return 1
    fi

    # Normalize shift to 0-25
    n=$(( (shift % 26 + 26) % 26 ))

    # Generate rotated alphabet
    local rotated="${alpha:n}${alpha:0:n}"

    echo "$text" | tr "a-z" "$rotated"
}

rotl() {
    if [[ -n $1 ]] ; then
        size=${#1}

        if [[ "$size" > 25 ]] && [[ "$size" < 51 ]] ; then
            echo "reduce size by 25"
            size=$((size - 25))
        fi

        # if there is a second argument, only the rotation will be printed
        if [[ -n $2 ]] ; then
            rot $size $1
        else
            # https://stackoverflow.com/questions/20871534/concatenate-in-bash-the-output-of-two-commands-without-newline-character
            { echo "rot +$size: "; rot $size $1; } | tr "\n" " "
            echo
            { echo "rot -$size: "; rot -$size $1; } | tr "\n" " "
            echo
        fi

    fi
}

rote() {
    input="${1//./}"
    rote36rotl "$input"
}

rote36rotl() {
    if [[ -n $1 ]] ; then

        # datestamp as base 36
        datestamp=$(date +%y%m%d)_

        year=$(decimal_to_base36_wrap $(date +%y))
        month=$(decimal_to_base36 $(date +%m))
        day=$(decimal_to_base36 $(date +%d))

        datestamp=${year}${month}${day}_
        datestamp=`echo "${datestamp}" | tr '[A-Z]' '[a-z]'`

        # the last part as: rotate the length (if string is 5 long rotate 5, if length is 6 rotate 6, etc)
        rotl=$(rotl $1 0)
        emailaddress=$datestamp$rotl"@reduxmail.com"
        echo $emailaddress

    fi
}

# claud ai
drote() {
    local email="$1"

    # Strip @reduxmail.com
    local local_part="${email%@reduxmail.com}"

    # Split on _ → datestamp and encoded parts
    local ds="${local_part%%_*}"
    local encoded="${local_part#*_}"

    # --- Base36 char to decimal ---
    _b36_to_dec() {
        local c="${1,,}"  # lowercase
        if [[ "$c" =~ [0-9] ]]; then
            echo "$c"
        else
            # a=10, b=11, ... z=35
            # ASCII of a is 97; 97 - 87 = 10 ✓
            printf "%d" $(( $(printf '%d' "'$c") - 87 ))
        fi
    }

    # --- Decode datestamp (3 base36 chars → YYMMDD) ---
    local yy mm dd yymmdd
    yy=$(_b36_to_dec "${ds:0:1}")
    mm=$(_b36_to_dec "${ds:1:1}")
    dd=$(_b36_to_dec "${ds:2:1}")
    yymmdd=$(printf "%02d%02d%02d" "$yy" "$mm" "$dd")

    # --- Reverse the rot cipher in pure bash ---
    local size=${#encoded}
    if (( size > 25 && size < 51 )); then
        size=$(( size - 25 ))
    fi
    local shift=$(( size % 26 ))

    local decoded="" i c ascii base rotated
    for (( i = 0; i < ${#encoded}; i++ )); do
        c="${encoded:$i:1}"
        ascii=$(printf '%d' "'$c")
        if (( ascii >= 97 && ascii <= 122 )); then
            # lowercase: base = 97
            rotated=$(( (ascii - 97 - shift + 26) % 26 + 97 ))
            decoded+=$(printf "\\$(printf '%03o' "$rotated")")
        elif (( ascii >= 65 && ascii <= 90 )); then
            # uppercase: base = 65
            rotated=$(( (ascii - 65 - shift + 26) % 26 + 65 ))
            decoded+=$(printf "\\$(printf '%03o' "$rotated")")
        else
            decoded+="$c"
        fi
    done

    echo "$yymmdd: $decoded"
}

# ---
# searching
# ---

# find a file (faf)
faf() {
     path="."
     if [[ -n $2 ]]; then
          path=$2
     fi
     find ${path} -type f -iname ${1} 2>/dev/null
}

# find in file (fif) | https://stackoverflow.com/questions/16956810/find-all-files-containing-a-specific-text-string-on-linux
fif() {
     path="."
     if [[ -n $2 ]]; then
          path=$2
     fi
     grep -rnw ${path} -e ${1} 2>/dev/null
}


# ---
# web++
# ---


# ajp related
# ---
# ajp-cp2dropbox() {
#   "/home/poq/syncDir/repos/git/gi.op.fo/miniProjects/2106_ajpDropboxDeployer/archi.sh" "$1" "$2"
# }
podigy() {
    cd /home/poq/syncDir/repos/git/gi.op.fo/podigy/src
    source venv/bin/activate
    python archi.py -s /home/poq/syncDir/repos/git/gi.op.fo/fiodb/db/podigy/sites
    deactivate
}
# podigy-pywsdb() {
#   podigy
#   /home/poq/syncDir/repos/git/gi.op.fo/pyws/deploy/deployToBuildServer.sh db
# }


# jeton
# ---
jeton() {
    cd /home/poq/syncDir/repos/git/gi.op.fo/jeton/src/
    source venv/bin/activate
    python archi.py -s /home/poq/syncDir/repos/git/gi.op.fo/fiodb/db/jeton/in/sites -r $1
    deactivate
}


# misc websites
# ---
alias 00101111.xyz-deploy="rsync -v -a --progress --stats --delete-delay -e 'ssh -p 1808' /home/poq/syncDir/repos/git/gi.op.fo/00101111.xyz/www/ usr@weba:/var/www/00101111.xyz/"
alias factor.red-deploy="rsync -v -a --progress --stats --delete-delay -e 'ssh -p 1808' /home/poq/syncDir/repos/git/gi.op.fo/mini-websites/factor.red/ usr@weba:/var/www/factor.red/"
alias op.fo-deploy="rsync -v -a --progress --stats --delete-delay -e 'ssh -p 1808' /home/poq/syncDir/repos/git/gi.op.fo/mini-websites/op.fo/ usr@weba:/var/www/op.fo/"
alias wa.fo-deploy="rsync -v -a --progress --stats --delete-delay -e 'ssh -p 1808' /home/poq/syncDir/repos/git/gi.op.fo/mini-websites/wa.fo/ usr@weba:/var/www/wa.fo/"


# jongleur
# ---
jcssbuilder() {
    cd /home/poq/syncDir/repos/git/gi.op.fo/jCssBuilder/src
    source venv/bin/activate
    python /home/poq/syncDir/repos/git/gi.op.fo/jCssBuilder/src/archi.py
    deactivate
}
jongleur-activate() {
    cd /home/poq/syncDir/repos/git/gitlab.com/jongleur/src
    source venv/bin/activate
}
jump-to-downloads() {
    cd /home/poq/syncDir/0_downloads
}
ajp.fm-build() {
    jongleur-activate
    /home/poq/syncDir/repos/git/gi.op.fo/ajp.fm/jongleur/run.sh
    deactivate
    jump-to-downloads
}
ajp.fm-build-all() {
    jongleur-activate
    /home/poq/syncDir/repos/git/gi.op.fo/ajp.fm/jongleur/runAll.sh
    deactivate
    jump-to-downloads
}
alias ajp.fm-deploy="rsync -v -a --progress --stats --delete-delay -e 'ssh -p 1808' /home/poq/syncDir/repos/git/gi.op.fo/ajp.fm/jongleur/html_export/ usr@178.156.192.201:/var/www/ajp.fm/jongleur/"
antijanteboka.com-build() {
    jongleur-activate
    /home/poq/syncDir/repos/git/gi.op.fo/antijanteboka.com/jongleur/run.sh
    deactivate
    jump-to-downloads
}
antijanteboka.com-build-all() {
    jongleur-activate
    /home/poq/syncDir/repos/git/gi.op.fo/antijanteboka.com/jongleur/runAll.sh
    deactivate
    jump-to-downloads
}
alias antijanteboka.com-deploy="rsync -v -a --progress --stats --delete-delay -e 'ssh -p 1808' /home/poq/syncDir/repos/git/gi.op.fo/antijanteboka.com/jongleur/html_export/ usr@178.156.192.201:/var/www/antijanteboka.com/jongleur/"
antijantemiriam.com-build() {
    jongleur-activate
    /home/poq/syncDir/repos/git/gi.op.fo/antijantemiriam.com/jongleur/run.sh
    deactivate
    jump-to-downloads
}
antijantemiriam.com-build-all() {
    jongleur-activate
    /home/poq/syncDir/repos/git/gi.op.fo/antijantemiriam.com/jongleur/runAll.sh
    deactivate
    jump-to-downloads
}
alias antijantemiriam.com-deploy="rsync -v -a --progress --stats --delete-delay -e 'ssh -p 1808' /home/poq/syncDir/repos/git/gi.op.fo/antijantemiriam.com/jongleur/html_export/ usr@178.156.192.201:/var/www/antijantemiriam.com/jongleur/"
billgoats.com-build() {
    jongleur-activate
    /home/poq/syncDir/repos/git/gi.op.fo/billgoats.com/jongleur/run.sh
    deactivate
    jump-to-downloads
}
billgoats.com-build-all() {
    jongleur-activate
    /home/poq/syncDir/repos/git/gi.op.fo/billgoats.com/jongleur/runAll.sh
    deactivate
    jump-to-downloads
}
alias billgoats.com-deploy="rsync -v -a --progress --stats --delete-delay -e 'ssh -p 1808' /home/poq/syncDir/repos/git/gi.op.fo/billgoats.com/jongleur/html_export/ usr@178.156.192.201:/var/www/billgoats.com/jongleur/"
curious.art-build() {
    jongleur-activate
    /home/poq/syncDir/repos/git/gi.op.fo/curious.art/jongleur/run.sh
    deactivate
    jump-to-downloads
}
curious.art-build-all() {
    jongleur-activate
    /home/poq/syncDir/repos/git/gi.op.fo/curious.art/jongleur/runAll.sh
    deactivate
    jump-to-downloads
}
alias curious.art-deploy="rsync -v -a --progress --stats --delete-delay -e 'ssh -p 1808' /home/poq/syncDir/repos/git/gi.op.fo/curious.art/jongleur/html_export/ usr@178.156.192.201:/var/www/curious.art/jongleur/"
curiouscreators.com-build() {
    jongleur-activate
    /home/poq/syncDir/repos/git/gi.op.fo/curiouscreators.com/jongleur/run.sh
    deactivate
    jump-to-downloads
}
curiouscreators.com-build-all() {
    jongleur-activate
    /home/poq/syncDir/repos/git/gi.op.fo/curiouscreators.com/jongleur/runAll.sh
    deactivate
    jump-to-downloads
}
alias curiouscreators.com-deploy="rsync -v -a --progress --stats --delete-delay -e 'ssh -p 1808' /home/poq/syncDir/repos/git/gi.op.fo/curiouscreators.com/jongleur/html_export/ usr@178.156.192.201:/var/www/curiouscreators.com/jongleur/"
frodr.com-build() {
    jongleur-activate
    /home/poq/syncDir/repos/git/gi.op.fo/frodr.com/jongleur/run.sh
    deactivate
    jump-to-downloads
}
frodr.com-build-all() {
    jongleur-activate
    /home/poq/syncDir/repos/git/gi.op.fo/frodr.com/jongleur/runAll.sh
    deactivate
    jump-to-downloads
}
alias frodr.com-deploy="rsync -v -a --progress --stats --delete-delay -e 'ssh -p 1808' /home/poq/syncDir/repos/git/gi.op.fo/frodr.com/jongleur/html_export/ usr@178.156.192.201:/var/www/frodr.com/jongleur/"
klevstul.com-build() {
    jongleur-activate
    /home/poq/syncDir/repos/git/gi.op.fo/klevstul.com/jongleur/run.sh
    deactivate
    jump-to-downloads
}
klevstul.com-build-all() {
    jongleur-activate
    /home/poq/syncDir/repos/git/gi.op.fo/klevstul.com/jongleur/runAll.sh
    deactivate
    jump-to-downloads
}
alias klevstul.com-deploy="rsync -v -a --progress --stats --delete-delay -e 'ssh -p 1808' /home/poq/syncDir/repos/git/gi.op.fo/klevstul.com/jongleur/html_export/ usr@weba:/var/www/klevstul.com/jongleur/"
