#!/bin/bash
if [ -z `which Xdialog` ]
then
  gksu apt-get install xdialog
fi
if [ -z `which curl` ] 
then
  echo "you need curl, installing curl..."
  gksu apt-get install curl
fi 

# logging in if needed
up=$(Xdialog --stdout --title "freizeitparkweb login"    --password     --2inputsbox "FZPW login" 0 0 "username" "" "passwort" "")
username=$(echo "$up"|cut -d/ -f1)
password=$(echo "$up"|cut -d/ -f2)

(
echo -e "XXX\nlogging in ...\nXXX\n0"
curl -F cmd=login \
     -F az=login \
     -F "Username=$username" \
     -F "Password=$password" \
     --cookie-jar ~/.curlcookies \
     http://freizeitparkweb.de/cgi-bin/dcf/dcboard.cgi?az=login >/dev/null
max=$#
n=1
for i in $* 
do
  destfile="/tmp/$i$$"
  tempfile="$i"
  if [ "$(exiftran -d "$i"|awk '/Orientation/ && $3 != "top" && $5 != "left"')" != "" ]
  then
    tempfile="/tmp/r$i$$"
    echo -e "XXX\nRotating $i...\nXXX\n$((100*n/max))"
    exiftran -a -o "$tempfile" "$i"
    if test $? -ne 0; then
      echo -e "XXX\nError while transforming $i - skipped.\nXXX\n$((100*n/max))";sleep 5
      if [ -f "$tempfile" ] ; then rm "$tempfile"; fi
      tempfile="$i"
    fi
  fi
  echo -e "XXX\nResizing $i ...\nXXX\n$((100*n/max))"
  convert -geometry 800x800 -quality 85 "$tempfile" jpg:"$destfile"
#  ls -l /tmp/$i$$
  echo -e "XXX\nUploading $i ...\nXXX"
  url=$(
    curl --referer 'http://freizeitparkweb.de/cgi-bin/dcf/dcboard.cgi?az=upload_file&forum=' \
       -F az=upload_file \
       -F command=save \
       -F file_upload=@"$destfile" \
       -F file_type=jpg \
       --cookie ~/.curlcookies \
       'http://freizeitparkweb.de/cgi-bin/dcf/dcboard.cgi?az=upload_file&forum='  |
    awk '/http:/&&/href/{sub("^href=\"","",$3);sub("\"$","",$3);print $3}' 
  )
  urls="$urls"$'\n'"$url"
  echo $((100*n/max))
  n=$((n+1))
  if [ -f "$destfile" ] ; then rm "$destfile"; fi
  if [ -f "$tempfile" ] && [ "$tempfile" != "$i" ] ; then rm "$tempfile" ; fi
done   
echo "101"
echo "$urls"| Xdialog -title "freizeitparkweb upload" -no-cancel -textbox - 10 60
)| Xdialog -title "freizeitparkweb upload" -no-cancel -gauge status 10 30
