#!/bin/bash

INTERVAL="10"
FAILURE_PAUSE="10"
BASE_PATH="/var/lib/photobox"

BASE_URL="https://fotobox.online/upload"
#BASE_URL="http://fotobox.online:8888/upload"
#BASE_URL="http://10.50.0.30:8888/upload"

FOTOBOX_ID="1"
FOTOBOX_KEY="eDAOMohrcJY3"



cd "$BASE_PATH/events"

while true; do
	date=$(date +'%Y-%m-%d %H:%M:%S')
	
	todos="$(ls ./*/todo/* 2> /dev/null)"
	if [ "$todos" != "" ]; then
		echo -e "= CONVERTING ==================================\n"
		for todo in $todos; do
			echo "CONVERTING: $todo"
			
			event_id=$(echo "$todo" | cut -d'/' -f2)
			filename=$(echo "$todo" | cut -d'/' -f4)
			
			mkdir -p "./$event_id/lowres" 2> /dev/null
			mkdir -p "./$event_id/upload" 2> /dev/null
			
			lowres="./$event_id/lowres/$filename"
			upload="./$event_id/upload/$filename"
			
			( convert "$todo" -resize 1000x -quality 0.7 "$lowres"  && cp "$lowres" "$upload"  && rm -f "$todo" && echo "OK" ) || echo "FAIL!"
			
			echo ""
		done
	fi
	
	uploads="$(ls ./*/upload/* 2> /dev/null)"
	if [ "$uploads" != "" ]; then
		echo -e "= UPLOADING ===================================\n"
		for upload in $uploads; do
			echo "UPLOADING: $upload"
			
			event_id=$(echo "$upload" | cut -d'/' -f2)
			filename=$(echo "$upload" | cut -d'/' -f4)
			
			timestamp_fotobox=$(date +'%Y-%m-%dT%H:%M:%S.%N%z')
			timestamp_shot=$(basename "$upload" | sed 's|.jpg||g')
			url="$BASE_URL/$FOTOBOX_ID/$FOTOBOX_KEY/$event_id/$timestamp_fotobox/$timestamp_shot/"
			#~ echo "$url"
			
			result=$(curl -s --form "image=@$upload" "$url" 2>&1)
			if [ "$result" == "OK" ]; then
				( rm -f "$upload" && echo "OK" ) || echo "FAIL!"
			else
				echo "$result"
				sleep $FAILURE_PAUSE
			fi
			echo ""
		done
	fi
	
	# SLEEP
	sleep $INTERVAL
done
