#!/bin/bash

unset CDPATH
set -u
set +o histexpand

URL="http://pixelbanane.de/yafu"

EMAIL=""
PASSWORD=""
COMMENT=""
HIDDEN=""
FILENAME=""

while getopts ":c:p:e:hHf:" OPTION; do
   case "$OPTION" in
      'c')
         COMMENT="$OPTARG"
         ;;

      'p')
         PASSWORD="$OPTARG"
         ;;

      'e')
         EMAIL="$OPTARG"
         ;;

      'H')
         HIDDEN="-F hidden=true"
         ;;

      'f')
         FILENAME="$OPTARG"
         ;;

      'h')
         cat << EOF
Usage: $0 [OPTIONS] FILE

OPTIONS
   -c COMMENT
   -p PASSWORD
   -e EMAIL
   -h show help
   -H hide file in file list
   -f FILENAME (use FILENAME instead of basename(FILE))
EOF
         exit 0
         ;;

      '?')
         echo "Unknown option: -$OPTARG"
         exit 1
         ;;

      ':')
         echo "Option -$OPTARG needs an argument"
         exit 1
         ;;
   esac
done

shift $(( OPTIND - 1 ))

if (( $# == 0 )) ; then
   echo "Missing file"
   exit 1
elif (( $# > 1 )) ; then
   echo "Too many arguments"
   exit 1
fi

UPLOAD_IDENTIFIER=$( wget -qO- "$URL" | sed -nr 's/.*name="UPLOAD_IDENTIFIER" value="([^"]+)".*/\1/p' )

FILE="$1"

if ! [[ "$FILENAME" ]] ; then
   FILENAME=$(basename "$FILE")
fi

EXPIRES="max"

OUT=$(
curl \
   -# \
   -F "email=$EMAIL" \
   -F "expires=$EXPIRES" \
   -F "comment=$COMMENT" \
   -F "filename=$FILENAME" \
   -F "password=$PASSWORD" \
   -F "upload=@$FILE" \
   $HIDDEN \
   "$URL/index.php"
)

ID_AND_FILE=$(sed -nr 's!.*href="/yafu/info/([0-9]+/[^"]+).*!\1!p' <<< "$OUT")

DIRECT_LINK="$URL/$ID_AND_FILE"
INFO_LINK="$URL/info/$ID_AND_FILE"

DELETION_LINK=$(sed -nr 's!.*(http://.+/delete/[^"]+).*!\1!p' <<< "$OUT")

echo "Download Link: $DIRECT_LINK"
echo "Info Link: $INFO_LINK"
echo "Deltion Link: $DELETION_LINK"
