#! /usr/bin/env bash
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
USER_HOME=$HOME
[[ -n "${SUDO_USER}" ]] && USER_HOME="$(eval "echo ~${SUDO_USER}")"
. ${SHRC_D:-$SCRIPT_DIR}/01_util.functions 

set -e

[[ -n $(type -p heavyscript) ]] \
|| curl -s https://raw.githubusercontent.com/Heavybullets8/heavy_script/main/functions/deploy.sh | bash

if [[ $USER == "$(sudo bash -c "echo \$SUDO_USER")" ]]; then

    if [[ -z "$(type -p apt)" || -n "$UPGRADE" ]]; then
    echo "sudo action section begins..."
        [[ -z $(type -p heavyscript) ]] && echo "heavyscript isn't installed!" \
        || sudo heavyscript enable --apt

        sudo update-alternatives --remove vim.tiny /usr/bin/vim.tiny || true
        sudo apt update
        sudo apt remove vim-tiny
        sudo apt install fzf neovim fd-find ripgrep
        sudo apt install atool caca-utils figlet zip
        sudo apt install --yes mediainfo exiftool mupdf-tools cmigemo dict dict-wn dictd libsixel-bin xsel
        # sudo apt install w3m-el xdg-utils unoconv
        sudo apt install --yes ranger
    echo "sudo section done."
    fi
else
    printf '%s\n' \
        "sudo failed to run, please make sure user $USER is allowed to run sudo and run again." \
        'continuing to non-sudo actions...'
fi

echo 'Normalizing git config...'
git_config() {
    local SCOPE="${SCOPE:-global}"
    [[ -n "$(git config "${1}")" ]] \
    || git config "--${SCOPE}" "${@}"
}
git_config core.editor nvim
git_config pull.ff     only
git config --list --show-scope

[[ -n "$(type -p 'webi')" ]] || curl -sS https://webi.sh/ | sh

cat << LOADENVMAN > ~/.config/envman/load.sh
if [ -z "\$ENVMAN_LOADED" ]; then
    ENVMAN_LOADED=1

    # Generated for envman. Do not edit.
    for x in ~/.config/envman/*.env; do
        my_basename="\$(basename "\${x}")"
        if [ "*.env" = "\${my_basename}" ]; then
            continue
        fi

        if [[ -n "\${DBG}" ]]; then
            echo "Loading \${x}..."
            \${DBG/^1/:}
        fi
        # shellcheck source=/dev/null
        . "\${x}"
    done

fi

OLDPATH="\$PATH"; NEWPATH=""; colon=""
while [ "\${OLDPATH#*:}" != "\$OLDPATH" ]; do
    entry="\${OLDPATH%%:*}"; search=":\${OLDPATH#*:}:"
    [ "\${search#*:\$entry:}" == "\$search" ] && NEWPATH="\$NEWPATH\$colon\$entry" && colon=:
    OLDPATH="\${OLDPATH#*:}"
done
NEWPATH="\$NEWPATH:\$OLDPATH"
export PATH="\$NEWPATH"
unset NEWPATH OLDPATH colon entry search
LOADENVMAN

cat << ADDPATH > ~/.config/envman/PATH_truestuff.env
PATH="$SCRIPT_DIR:\$PATH"
ADDPATH

cat << SHELLREFRESH >  ~/.config/envman/shell-refresh.env
alias _r="exec \$SHELL -l "
SHELLREFRESH

printf '%s\n' '' '' \
    "$(basename "$0") is a user envrionment initialization script for TrueNAS SCALE" \
    '' \
    'Initialization done, ready to reload your shell' \
    '' \
    'Run the following:' \
    "exec \$SHELL -l "