#!/bin/bash

red='\033[0;31m'
green='\033[0;32m'
nocolor='\033[0m'

TEST_VALUE='HELLO WORLD!'

run_test() {
    cd $source_files/$1
    printf "\n${1}:\n"
    if ($basedir/gradlew-fdroid 2>/dev/null || true) | grep -Fo "$2"; then
	printf "${green}passed: $1\n"
    else
	printf "${red}ERROR: $2 not found in $1\n"
	((exit_value++))
    fi
    printf $nocolor
}

download_cache_test() {
    if $basedir/gradlew-fdroid helloWorld 2>/dev/null | grep -F "$TEST_VALUE"; then
	printf "${green}passed: $1\n"
    else
	printf "${red}ERROR: \n"
	$basedir/gradlew-fdroid helloWorld
	((exit_value++))
    fi
    printf $nocolor
}

exit_value=0
basedir=$(cd $(dirname $0)/..; pwd)
source_files=$basedir/tests/source-files
export https_proxy=127.7.7.7:7 # fake proxy to block downloading

run_test osmandapp/osmand 2.2.1
run_test com.integreight.onesheeld 3.3
run_test se.manyver/android 5.5
run_test yuriykulikov/AlarmClock 5.1.1

printf "\n\nforce test files to have Windows linefeeds:\n"
tmpdir=`mktemp -d`
cp -a $source_files/osmandapp $source_files/yuriykulikov $tmpdir/
awk 'sub("$", "\r")' \
    $source_files/yuriykulikov/AlarmClock/gradle/wrapper/gradle-wrapper.properties \
    > $tmpdir/yuriykulikov/AlarmClock/gradle/wrapper/gradle-wrapper.properties
awk 'sub("$", "\r")' \
    $source_files/osmandapp/osmand/build.gradle \
    > $tmpdir/osmandapp/osmand/build.gradle
source_files=$tmpdir

run_test yuriykulikov/AlarmClock 5.1.1
run_test osmandapp/osmand 2.2.1

cd $tmpdir
mkdir -p download_cache_test/gradle/wrapper
cd download_cache_test
echo 'distributionUrl=https\://services.gradle.org/distributions/gradle-0.7-bin.zip' \
     > gradle/wrapper/gradle-wrapper.properties
printf "task helloWorld {\n\tdoLast {\n\t\tprintln '$TEST_VALUE'\n\t}\n}" > build.gradle

export GRADLE_VERSION_DIR=$tmpdir/gradle/versions
mkdir -p $GRADLE_VERSION_DIR

unset https_proxy
printf "download, unpack, and run: "
download_cache_test 0.7
printf "unpack and run: "
rm -rf $GRADLE_VERSION_DIR/0.7/
download_cache_test 0.7
printf "just run: "
download_cache_test 0.7

exit $exit_value
