#!/bin/zsh
# Michael Weber 2014
# vim: expandtab tabstop=4

qr=
append=0
x=
HSHLINK=${HSHLINK:-hsh.link}

usage() {
    {
        echo "$@"
        echo "Usage: $0 [-x] [-qr] [-+] -in  [link]"
        echo "       $0 [-x] [-qr]      -out <link>"
    } >&2
    exit 1
}

while [ $# -gt 0 ] ; do
    case $1 in
        "-x")  shift; x=1;;
        "-qr") shift; qr=1;;
        "-+")  shift; append=1;;
        "-in") shift
            if [ $# -eq 1 ] ; then
                clip=$1
                shift
            else
                if  [ "$append" = "1" ] ; then
                    usage "Need clipboard to append to"
                fi
            fi
            [ $# -gt 0 ] && usage "Too many arguments"
            if [ -n "$x" ] ; then
                xclip -out \
                | if [ -n "$qr" ] ; then
                    curl -sF 'content=<-' -F append=$append \
                        -F output=qr_png ${HSHLINK}/${clip} | feh -
                else
                    out=$(curl -sF 'content=<-' -F append=$append \
                        -F output=long ${HSHLINK}/${clip})
                    echo $out
                    echo -n $out | xclip -in
                fi
            else
                cat \
                | if [ -n "$qr" ] ; then
                    curl -F 'content=<-' -F append=$append \
                        -F output=qr ${HSHLINK}/${clip}
                else
                    curl -F 'content=<-' -F append=$append \
                        -F output=long ${HSHLINK}/${clip}
                fi
            fi
            ;;
        "-out") shift
            if [ $# -eq 1 ] ; then
                clip=${1}
                shift
            else
                usage "Wrong number of link or hash given"
            fi
            if [ -n "$x" ] ; then
                if [ -n "$qr" ] ; then
                    curl -sf -F output=qr_png ${HSHLINK}/${clip} | feh -
                else
                    curl -sf -F output=raw ${HSHLINK}/${clip} | xclip -in
                fi
            else
                if [ -n "$qr" ] ; then
                    curl -f -F output=qr_utf8 ${HSHLINK}/${clip}
                else
                    curl -f -F output=raw ${HSHLINK}/${clip}
                fi 
            fi
            ;;
        *)
            usage "Unsupported option"
            ;;
    esac
done
