#!/bin/bash

if [[ "$1" == "--help" ]] ; then
    echo "Usage: sky-server.sh [PORT]"
    echo "Listens on given port (7075 by default)"
    echo "and forwards HTTP requests to Skynet copier."
    echo "HTTP response is gzipped tar archive with resource files"
    echo
    echo "On client side call:"
    echo "  curl -sS -H 'rbtorrent:1234567890ABCDEF' http://server:port/ | tar zxf -"
    exit 1
fi

PORT="$1"
PORT=${PORT:-"7075"}
FIFO=${FIFO:-"/tmp/$0.fifo"}
rm -rf "$FIFO"
mkfifo "$FIFO"
trap "rm -f $FIFO" EXIT
ulimit 0

while true ;  do
{
    # minial parse HTTP request, find rbtorrent: header
	LINE="x"
	RBTORRENT=""
	while [[ -n "${LINE/[ \n]/ }" ]] ; do
		read LINE<"$FIFO"
		LINE=${LINE%%$'\r'}
		if [[ "$LINE" =~ rbtorrent: ]] ; then
			RBTORRENT="$LINE"
		fi
	done
	echo -e "HTTP/1.1 200 OK"
	# download the resource and return it as gzipped tar archive
	if [[ -n "$RBTORRENT" ]] ; then
	    echo -e "Content-Type: application/gzip\r\n"
		FILES=(`sky files --json $RBTORRENT | grep -o -P '"name":\s"\K[^"]+'`)
		TMPDIR=`mktemp -d`
		chmod 0777 "$TMPDIR"
		sky get --dir="$TMPDIR" $RBTORRENT
		tar zcf - --directory "$TMPDIR" ${FILES[@]}
		rm -rf "$TMPDIR"
	else
	    echo -e "Content-Type: text/plain\r\n"
		echo Ok	
	fi
} | nc -6 -l -q 0 -p ${PORT} > "$FIFO"
done 
