#!/bin/bash
# Copyright 2007,2009,2010 Chris Forbes, Robert Pepperell, Matthew Bowra-Dean, Paul Chote, Alli Witheford.
# This file is part of OpenRA.
# 
#  OpenRA is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
# 
#  OpenRA is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
# 
#  You should have received a copy of the GNU General Public License
#  along with OpenRA.  If not, see <http://www.gnu.org/licenses/>.
#

# Internal options
RESOURCES_PATH=`pwd`/../Resources
SUPPORT_PATH=~/Library/"Application Support"/OpenRA

# Download and install game mix files from the internet
# args:
#    $1: package file
#    $2: location to unpack package
#    $3: package size
#    $4: mod name
#    $5: download url

PWD=`pwd`
if [ ! -d "$SUPPORT_PATH" ]; then
	mkdir -p "$SUPPORT_PATH"
fi

cd "$SUPPORT_PATH"
mkdir -p "${2}"

if [ -e "Downloads/${1}" ]; then
/usr/bin/osascript << EOT
	tell application "Terminal"
		activate
		do script "cd \"${SUPPORT_PATH}\"; unzip -o \"Downloads/${1}\" -d \"${2}\"; touch done; exit;"
	end tell
EOT
	# Hack around osascript returning before the download finishes
	while [ ! -e "done" ]; do
		sleep 1
	done
	rm "done"	
else
CONTINUE=`/usr/bin/osascript << EOT
	tell application "Finder"
		activate
		display dialog "OpenRA needs to download ${4}.\n\nDownload size: ${3}" \
			buttons {"Download", "Quit"} \
			default button "Download" \
			with icon alias (POSIX file "$RESOURCES_PATH/OpenRA.icns")
		set result to button returned of result
	end tell
EOT`
		if [ "$CONTINUE" != "Download" ]; then
			exit 1
		fi
		
/usr/bin/osascript << EOT
	tell application "Terminal"
		activate
		do script "cd \"${SUPPORT_PATH}\"; curl --create-dirs -o \"./Downloads/${1}\" \"${5}\"; unzip -o \"Downloads/${1}\" -d \"${2}\"; touch done; exit;"
	end tell
EOT
	# Hack around osascript returning before the download finishes
	while [ ! -e "done" ]; do
		sleep 1
	done
	rm "done"
fi