#!/usr/bin/bash
# SPDX-License-Identifier: CC0-1.0
# shrik3's ad-hoc pastebin

# USAGE : just pipe some output to this script
# echo "hello" | paste.sh <name-prefix>

##################################################################
# echo "YOU ARE NOT RUNNING A RAMDOM SCRIPT FROM INTERNET, ARE YOU?"
# exit 1
##################################################################

# url prefix, depends on webserver settings
URL_ROOT="https://wth.moe/volatile"
# documentation root on local fs
DOC_ROOT="/home/shrik3/docs/blog/vnoid_home"
# where are pastes stored
PB_ROOT=$DOC_ROOT/volatile/
# documentation root on remote server
REMOTE=shrik3@shrik3.com:/srv/www/wth.moe
# random string for fileneme
NAME="$(tr -dc A-Za-z0-9 </dev/urandom | head -c 7; echo).asc"
# derived
FILEPATH="${PB_ROOT}${NAME}"
URL="${URL_ROOT}/${NAME}"

bold=$(tput bold)
normal=$(tput sgr0)

if [ $# -eq 1 ]; then
    NAME="${1// /_}_${NAME}"    # replace space with underscore
fi

cd $DOC_ROOT

# rare, in case we have name clision
if [ -f $FILEPATH ]; then
    # TODO, automatically retry new rand filename
    echo "FILE ALREADY EXISTS...BAD LUCK. PLS TRY AGAIN"
    exit 1
fi

# in case of abort (SIGINT), remove the file if it is empty
cleanup() {
    echo "aborted"
    if [ ! -s "${FILEPATH}" ]; then
        echo "file empty, remove"
        rm -f -- "${FILEPATH}"
    fi
}

deploy() {
    # gen.sh generates a index using the tree program.
    # the script is here:  https://wth.moe/scripts/gen.sh
    ./scripts/render_site.sh
    scp -q "${FILEPATH}" "${REMOTE}/volatile/"
}

trap cleanup SIGINT
cat > "${FILEPATH}"
deploy
echo "${bold}${URL}${normal}"
