#!/bin/bash
USER="USERNAME"
PASS="PASSWORD"

if [[ "$USER" = "" ]] ; then
   echo "Edit the script and replace USERNAME and PASSWORD with your flickr username and password."
fi

if [[ "$@" != "" ]] ; then
   TAGS="${@}"
else
   TAGS=""
fi

function getFileList() {
   find . -maxdepth 1 -type f |grep -Ei 'jpg$|jpeg$|gif$|png$' |sort -r
}

function flickrCheckAuth() {
   url="http://www.flickr.com/tools/auth.gne"
   authXML=$(curl -s -F email="$USER" -F password="$PASS" $url 2>&1)

   #<limit>2147483648</limit> <used>8724031</used>
   LIMIT=$(echo $authXML|sed -n 's/.*<limit>\(.*\)<\/limit>.*/\1/p')
   USED=$(echo $authXML|sed -n 's/.*<used>\(.*\)<\/used>.*/\1/p')
   FREE=$(($LIMIT-$USED))

   if [ "$LIMIT" -gt "0" ] ; then
      echo "Authorized with $FREE bytes left to upload"
   else
      echo "Couldn't parse response."
   fi
}

function flickrUpload() {
   #Create the file so grep and >> don't complain.
   touch flickr.lst

   if grep "$1" flickr.lst ; then
      echo "Skipping file, it's been uploaded."
   else
      if [ -f "$1" ] ; then
         url="http://www.flickr.com/tools/uploader_go.gne"
         uploadXML=$(curl -s -F email="$USER" -F password="$PASS" -F photo="@$1" -F tags="$TAGS" $url 2>&1)
      else
         echo "File not found. $1"
      fi
      echo $uploadXML
      ID=$(echo $authXML|sed -n 's/.*<photoid>\(.*\)<\/photoid>.*/\1/p')

      echo "$ID $1" >>flickr.lst
   fi
}

flickrCheckAuth


# Get a list of images to upload to flickr.
while read FILE ; do
   echo $FILE
   flickrUpload "$FILE"

done < <( getFileList )


