#!/usr/bin/env bash

# TODO More integrated with current config

CACHE_DIR="${XDG_CACHE_DIR:-$HOME/.cache}/bsh"
FOLDER_NAME="geoffrey"
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )


mkdir -p "$CACHE_DIR"
if [ ! -f "${CACHE_DIR}/cmd" ]
then
    # Preparation
    WORK="${CACHE_DIR}/${FOLDER_NAME}"
    DEST="/tmp/${FOLDER_NAME}"
    mkdir "$WORK"

    # TODO Maybe we should just set HOME thereā€¦

    # Bashrc generation (sortable then unsortable)
    grep -o '^\s*[^#]*' $SCRIPT_DIR/.bsh/bashrc | sed 's/^\s\+//' > "${WORK}/b"
    echo "alias s='sudo -s -E bash --rcfile ${DEST}/b'" >> "${WORK}/b"
    echo "export VIMINIT='source ${DEST}/v'" >> "${WORK}/b"
    #echo "export TERMINFO=${DEST}/terminfo" >> "${WORK}/b"
    echo "export INPUTRC=${DEST}/i" >> "${WORK}/b"
    # Sort for compression efficiency (saves a whooping 12 bytes)
    sort -u "${WORK}/b" > "${WORK}/b_sorted"
    mv "${WORK}/b_sorted" "${WORK}/b"

    dircolors --sh >> "${WORK}/b"
    grep -o '^[^#]*' $SCRIPT_DIR/.bsh/bashrc_unsortable | sed 's/^\s\+//' >> "${WORK}/b"

    # Other files generation
    #mkdir -p "${WORK}/terminfo/${TERM:0:1}"
    #if [ -f "/usr/share/terminfo/${TERM:0:1}/${TERM}" ]
    #then
    #    cp "/usr/share/terminfo/${TERM:0:1}/${TERM}" "${WORK}/terminfo/${TERM:0:1}/${TERM}"
    #elif [ -f "$HOME/.config/terminfo/${TERM:0:1}/${TERM}" ]
    #then
    #    cp "$HOME/.config/terminfo/${TERM:0:1}/${TERM}" "${WORK}/terminfo/${TERM:0:1}/${TERM}"
    #fi
    grep -o '^\s*[^#]*' $SCRIPT_DIR/.bsh/inputrc | sed 's/^\s\+//' > "${WORK}/i"
    grep -o '^\s*[^"]*' $SCRIPT_DIR/.bsh/vimrc | sed 's/^\s\+//' > "${WORK}/v"

    # Creating entrypoint
    echo "bash --rcfile ${DEST}/b" > "${WORK}/e"
    echo "rm -rf ${DEST}" >> "${WORK}/e"
    # TODO Do not remove unless last one connected

    # Crafting command
    b64="$(cd "$CACHE_DIR"; tar czf - --sort=name "$FOLDER_NAME" | base64 -w 0)"
    echo "echo $b64|base64 -d|tar xzC /tmp" > "${CACHE_DIR}/cmd"
    # Due to magic, if the last command executed is bash, it disappears from the list of processes
    echo "sh ${DEST}/e" >> "${CACHE_DIR}/cmd"

    # Cleanup
    rm -rf "$WORK"

fi

# To keep until https://github.com/openssh/openssh-portable/commit/f64f8c00d158acc1359b8a096835849b23aa2e86
# is merged
function _ssh {
    if [ "${TERM}" = "alacritty" ]
    then
        TERM=xterm-256color ssh "$@"
    else
        ssh "$@"
    fi
}
alias ssh='_ssh'
_ssh -t "$@" "$(cat "${CACHE_DIR}/cmd")"