#!/bin/sh

REMOTE_REPO="rsync://ftp.idtech.space/ftp/frag-net/depots"

ARGS=$#

copy_game()
{
	if [ -f "/tmp/game_$1.csv" ]
	then
		rm "/tmp/game_$1.csv"
	fi

	curl -s "https://ftp.idtech.space/frag-net/depots/$1.csv" > "/tmp/game_$1.csv"

	# does this game offer more than one thing?
	if [ -f "/tmp/game_$1.csv" ]
	then

		echo "Pass the short version to this tool to begin downloading."
		echo "Games will be installed under $(pwd)/$1"
		echo ""

		cat "/tmp/game_$1.csv" | while read LINE
		do
			GAME_VERSION="$(echo "$LINE" | cut -d ',' -f 1)"
			GAME_TITLE="$(echo "$LINE" | cut -d ',' -f 2)"
			echo "$GAME_VERSION = $GAME_TITLE"
		done

		exit 0
	fi

	mkdir -p "$1/."
	rsync -rva --progress "$REMOTE_REPO/$1/." "$1/."
}

copy_version()
{
	if [ ! -f "/tmp/game_$1.csv" ]
	then

		echo "No version info for game $1 available."
		exit 1
	fi

	mkdir -p "$1/."

	cat "/tmp/game_$1.csv" | while read LINE
	do
		GAME_VERSION="$(echo "$LINE" | cut -d ',' -f 1)"
		GAME_TITLE="$(echo "$LINE" | cut -d ',' -f 2)"
		GAME_REMOTE="$(echo "$LINE" | cut -d ',' -f 3)"

		if [ "$GAME_VERSION" = "$2" ]
		then
			rsync -rva --progress "$REMOTE_REPO/$GAME_REMOTE/." "$1/."
		fi
	done
}

list_games()
{
	if [ -f /tmp/games.csv ]
	then
		rm /tmp/games.csv
	fi

	curl -s "https://ftp.idtech.space/frag-net/depots/games.csv" > /tmp/games.csv

	echo "Pass the short game name to this tool to begin downloading."
	echo "Games will be installed under $(pwd)"
	echo ""

	cat /tmp/games.csv | while read LINE
	do
		GAME_ID="$(echo "$LINE" | cut -d ',' -f 1)"
		GAME_TITLE="$(echo "$LINE" | cut -d ',' -f 2)"

		if [ ! -d "$GAME_ID" ]
		then
			echo "[ ] $GAME_ID ($GAME_TITLE)"
		else
			echo "[X] $GAME_ID ($GAME_TITLE)"
		fi
	done
}

if [ $ARGS -lt 1 ]
then
	list_games
else

	if [ $ARGS -lt 2 ]
	then
		copy_game "$1"
	else
		copy_version "$1" "$2"
	fi

fi
