#!/bin/bash
#
# dropbox-publish.sh
#
# publishes a file into dropbox, conveniently managed under subfolders
#

dropboxidfile="$(dirname "$0")/dropbox-id"

if [ ! -f "${dropboxidfile}" ]
then
	echo "cannot find ${dropboxidfile}"
	echo "please create this file, it shall only contain your numeric dropbox ID as found in public links, e.g. 66055976"
	exit 1
fi

dropboxid="$(cat ${dropboxidfile})"
inputfile="$1"
with_xclip="1"

if [ -z "$( which xclip )" ]
then
	echo "no xclip found, cannot copy public URL into clipboard" >/dev/stderr
	with_xclip=""
fi

if [ -z "${inputfile}" ]
then
	echo "usage: $0 <file> [directory]"
	exit 1
fi

if [ ! -f "${inputfile}" ]
then
	echo "error: ${inputfile} is not a regular file" >/dev/stderr
	exit 1
fi

year=$( date +%Y )
remote="https://dl.dropboxusercontent.com/u/${dropboxid}"
local="${HOME}/Dropbox/Public"
mime=$( file --brief --mime-type "${inputfile}" )
folder=""
ext3=$( basename "${inputfile}" |tail -c 5 )

if [ -n "$2" ]
then
	folder="$2"
	reason="of user input"
elif [ "$( basename "${inputfile}" |head -c 10 )" = "Screenshot" ]
then
	folder="screenshots"
	reason="filename starts with Screenshot"
elif [ "$( echo ${mime} |head -c 6 )" = "image/" ]
then
	folder="images"
	reason="mime type starts with image/"
elif [ "${mime}" = "text/plain" ]
then
	folder="text"
	reason="mime type is text/plain"
elif [ "$( echo ${mime} |head -c 5 )" = "text/" ]
then
    folder="code"
	reason="mime type starts with text/ but is not text/plain"
elif [ "${ext3}" = ".wad" -o "${ext3}" = ".pk3" -o "${ext3}" = ".pk7" ]
then
	folder="wads"
	reason="filename ends with .wad, .pk3 or .pk7"
else
	folder="misc"
	reason="no other rule matched"
fi

echo "using folder \"${folder}\" because ${reason}"

path="${year}/${folder}"
localdir="${local}/${path}"
mkdir -pv "${localdir}"
num=0
suffix=""

localbasename=$(basename "${inputfile}")
root=${localbasename%.*}
ext=${localbasename##*.}

if [ -n "${ext}" ]
then
	ext=".${ext}"
fi

while [ -f "${localdir}/${root}${suffix}${ext}" ]
do
	let num+=1
	suffix="-${num}"
done

filename="${root}${suffix}${ext}"
cp -iv "${inputfile}" "${localdir}/${filename}"

url="${remote}/${path}/$(echo "${filename}" |sed 's/ /%20/g')"

if [ "${with_xclip}" ]
then
	echo -n "${url}" |xclip
fi

echo "${url}"
