#!/usr/bin/env bash

##############################################################################
##
##  GitHub Upate script for Android Samples
##
##############################################################################

##replace with auth token for google-automerger GitHub account
TOKEN=herpderp

##make temporary dir to pull code into - delete at end.
mkdir github-temp
cd github-temp

##iterate through samples
for i in $(ls ../prebuilts/gradle);


##for testing
#foo="ActionBarCompat-Basic"
#foo="ActionBarCompat-Basic herpderp"
#foo="ActionBarCompat-Basic ActionBarCompat-ListPopupMenu"
#foo="MediaBrowserService MessagingService"
#for i in $foo;

do
echo "
$i"

URL=https://github.com/googlesamples/android-$i

result=$(curl -o /dev/null --silent --head --write-out '%{http_code}' "$URL")
#echo "$result $URL"

##checking to see if the repo exists
if [ "$result" != "200" ]; then
   echo "Cannot access repo for $i, it may not exist yet"
else
   echo "Updating repo for $i"

git clone $URL.git
##check to make sure it worked and the folder is there
if [ -d "android-$i" ]; then
   rsync -az --delete --exclude '*.git' ../prebuilts/gradle/$i/ ./android-$i/

   cd ./android-$i/

   git config user.name "google-automerger"
   git config user.email automerger@google.com

   git add .
   git status
   git commit -m "Auto-update"

   git remote set-url origin "https://$TOKEN@github.com/googlesamples/android-$i.git"
   git push origin master

  cd ..
else
   "Something went wrong when cloning $i - result directory does not exist."
fi

fi
done

##cleanup
cd ..
rm -rf ./github-temp