#!/bin/sh

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

# handle -h parameter
if [ "$1" = "-h" ]; then
    printf "Usage:\n"
    printf "  paste < text.txt         - read from stdin, generate filename\n"
    printf "  paste new.txt < file.txt - read from stdin with filename\n"
    printf "  paste file.txt           - upload file as is\n"
    return 0
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 ' /' '_')"
    cat > "${_file}"
    scp "${_file}" ${_ssh}:"${_remote_dir}/$(basename "${_file}")"
fi

printf "https://codevoid.de/h/p/$(basename "${_file}")\n"
printf "https://codevoid.de/h/p/$(basename "${_file}")" | xclip -i

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