#!/bin/bash

source "$(dirname $_)/shared.sh"

readonly MISCDIR="$(dirname $0)/misc"

GIT_REPOS=( 
	"NumberPicker git://github.com/mrn/numberpicker.git lib" 
	"DragSortListView git://github.com/bauerca/drag-sort-listview.git library"
	"ActionBarSherlock git://github.com/JakeWharton/ActionBarSherlock.git actionbarsherlock"
	"ShowcaseView git://github.com/jclehner/ShowcaseView.git library"
	"NineOldAndroids git://github.com/JakeWharton/NineOldAndroids.git library"
#	"HoloEverywhere https://github.com/Prototik/HoloEverywhere library"
)

THIRDPARTY=thirdparty
ZIPFILE=thirdparty.zip

DEFAULT_BUILDCOMMANDS=(
	com.android.ide.eclipse.adt.ResourceManagerBuilder
	com.android.ide.eclipse.adt.PreCompilerBuilder
	com.android.ide.eclipse.adt.ApkBuilder
	org.eclipse.jdt.core.javabuilder
)

DEFAULT_NATURES=( 
	com.android.ide.eclipse.adt.AndroidNature 
	org.eclipse.jdt.core.javanature 
)

# clone_or_fetch(string repoUrl, string targetDirectory)
clone_or_fetch()
{
	if [[ $UPDATE -eq 1 ]]; then
		( cd "$2" && git fetch) || exit 1
	else
		if [[ -d "$2" ]]; then
			die "ERROR: Directory $2 already exists. Run \`$(basename $0) update' instead'"
		fi
		git clone --depth 1 "$1" "$2" || exit 1
	fi
}

create_dotproject()
{
	local file="$1/.project"

	if [[ -e "$file" ]]; then
		echo "INFO: Not overwriting $file"
		return 0
	fi

	cat > "$file" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
	<name>$TARGET</name>
	<comment></comment>
	<projects>
	</projects>
	<buildSpec>
EOF

	for CMD in ${DEFAULT_BUILDCOMMANDS[@]}; do
		cat >> "$file" <<EOF
		<buildCommand>
			<name>$CMD</name>
			<arguments>
			</arguments>
		</buildCommand>
EOF
	done

	echo -e "\t</buildSpec>\n\t<natures>" >> "$file"


	for NATURE in ${DEFAULT_NATURES[@]}; do
		echo -e "\t\t<nature>$NATURE</nature>" >> "$file"
	done

	echo -e "\t</natures>\n</projectDescription>" >> "$file"

	echo "INFO: created $file"
}

create_dotclasspath()
{
	local file="$1/.classpath"

	if [[ -e "$file" ]]; then
		echo "INFO: Not overwriting $file"
		return 0
	fi

	cat > "$file" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
	<classpathentry kind="src" path="src/" />
	<classpathentry kind="src" path="gen/" />
	<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK" />
	<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
	<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
	<classpathentry kind="output" path="bin/classes" />
</classpath>
EOF

	echo "INFO: created $file"
}

create_lint_xml()
{
	local file="$1/lint.xml"

	if [[ -e "$file" ]]; then
		echo "WARNING: Overwriting $file"
	else
		echo "INFO: creating $file"
	fi

	cp "../${MISCDIR}/lint-ignoreall.xml" "$file"
}

create_project_files()
{
	create_dotproject "$1"
	create_dotclasspath "$1"
	create_lint_xml "$1"

	mkdir -p "$1/bin" "$1/gen"
}

fix_project_properties()
{
	ised -e 's/target=Google Inc.:Google APIs:([[:digit:]]+)/target=android-\1/g' "$1/project.properties"
}

link_or_copy()
{
	# Eclipse 3.6 under Mac OS X 10.7 doesn't like Android library dependencies
	# that are softlinks, apparently.
	case $(uname -s) in 
		Darwin|MINGW*)
			echo -n "Copying files to $2... "
			run cp -r "$1" "$2"
			echo "done"
			;;
		*)
			ln -sf "$1" "$2"
			;;
	esac
}

if ! command -v git &> /dev/null; then
	die "ERROR: git is required to run this script"
fi

UPDATE=0

if [[ $# -gt 0 ]]; then
	if [[ "$1" == "update" ]]; then
		UPDATE=1
	elif [[ "$1" == "cleanup" ]]; then
		run rm -rf ${THIRDPARTY}
		run mkdir ${THIRDPARTY}
		echo "INFO: Emptied directory \`${THIRDPARTY}'"
		exit 0
	fi
fi


run mkdir -p ${THIRDPARTY}
cd ${THIRDPARTY} || exit 1

ZIPDIRS=

for REPO in "${GIT_REPOS[@]}"; do
	
	read -ra REPO_INFO <<< "${REPO}"
	TARGET=${REPO_INFO[0]}
	URL=${REPO_INFO[1]}
	LIBDIR=${REPO_INFO[2]}

	if [[ -z ${TARGET} || -z ${URL} ]]; then
		die "No URL or LIBDIR in ${REPO_INFO[@]}"
	fi

	if [[ -z "${LIBDIR}" ]]; then
		clone_or_fetch "${URL}" "${TARGET}"
		fix_project_properties "${TARGET}"
		create_project_files "${TARGET}"
	else
		CLONEDIR=".${TARGET}Git"
		clone_or_fetch "${URL}" "${CLONEDIR}"
		link_or_copy "${CLONEDIR}/${LIBDIR}" "${TARGET}"
		fix_project_properties "${TARGET}"
		#create_project_files "${TARGET}"
	fi

	for LIB in $(find ${TARGET} -name android-support-v4.jar); do
		echo "INFO: Replacing android-support-v4.jar in $(dirname "${LIB}")"
		cp "../libs/android-support-v4.jar" "${LIB}"
	done

	#if [[ -f ${TARGET}/libs/android-support-v4.jar ]]; then
	#	echo "INFO: Replacing android-support-v4.jar in ${TARGET}"
	#	rm "${TARGET}/libs/android-support-v4.jar"
	#	cp "../libs/android-support-v4.jar" "${TARGET}/libs/android-support-v4.jar"
	#fi

	ZIPDIRS+="${THIRDPARTY}/${TARGET} "

	android update lib-project -p "${TARGET}"

	if [[ "${TARGET}" == "ShowcaseView" ]]; then
		echo >> "${TARGET}/project.properties" "android.library.reference.1=../NineOldAndroids"
	fi
done

cd - &> /dev/null

rm -f ${ZIPFILE}
run zip -q -r ${ZIPFILE} ${ZIPDIRS}

ZIPSIZE=$(stat -c %s ${ZIPFILE})
let ZIPSIZE=${ZIPSIZE}/1024

echo "Created ${ZIPFILE}: ${ZIPSIZE} kB"

echo
echo "=========================================================================="
echo "YOU NEED TO MANUALLY IMPORT THE DOWNLOADED SOURCES INTO AN ECLIPSE PROJECT"
echo "=========================================================================="





