#!/bin/sh
# needs: col, date, pwgen, ssh, xclip, notify-send, tee, tr

# configuration
_ssh="sdk@codevoid.de"
_remote_dir="/home/www/htdocs/http/p"
_web_location="https://codevoid.de/h/p"

# handle -h parameter
if [ "$1" = "-h" ]; then
    printf "Usage:\n"
    printf "  hpaste < text.txt         - read from stdin, generate filename\n"
    printf "  hpaste new.txt < file.txt - read from stdin with filename\n"
    printf "  hpaste file.txt           - upload file as is\n"
    exit 2
fi

# if there is no parameter: read STDIN
if [ -z "${1}" ]; then
    # read stdin into some fancy file
    _file="/tmp/$(date +"%Y-%m-%d_%M-%S")-$(pwgen -1 4 -A -0).txt"
    cat > "${_file}"
    # upload it
    scp "${_file}" ${_ssh}:"${_remote_dir}/$(basename "${_file}")"

# we have a parameter, and it is a file
elif [ -f "${1}" ]; then
    # normalize filename
    _file="$(readlink -f "${1}")"
    chmod 644 "${_file}"
    scp "${_file}" ${_ssh}:"${_remote_dir}/$(basename "${_file}")"

# we have a parameter, but it is no file (let's read STDIN again, and
# use the parameter as filename)
else
    _file="/tmp/$(printf '%s' "${1}" | col -b | tr -s ' /' '_' | head -n 1)"
    cat > "${_file}"
    scp "${_file}" ${_ssh}:"${_remote_dir}/$(basename "${_file}")"
fi

printf "${_web_location}/$(basename "${_file}")\n" \
    | tee | tr -d '\n' | xclip -i

[ -z $DISPLAY ] || notify-send "$(xclip -o)"
