#!/bin/bash

########################################
# Configurations

BINTOOL_GIT=https://github.com/acquia/DevDesktopCommon.git
PHP_VER=5.4.41-nts-Win32-VC9-x86
# NOTE there in also "5.5" string in the download url. Change it if upgrading to 5.6
MYSQL_VER=5.5.41-win32
# goes to composer require command
DRUSH_VER=7.0.0

TOPDIR=windrush

########################################
# Utils

fail() {
  echo "$1">&2
  kill -s TERM $$
}

replace_in_file() {
  sed "s/$1/$2/" "$3" > aa.tmp
  mv aa.tmp "$3"
}

enable_php_extension() {
  for a in $1 ; do
    replace_in_file ";extension=php_$a.dll" "extension=php_$a.dll" "$2"
  done
}


########################################
# Prepare $TOPDIR dir

[ -e $TOPDIR ] && ( rm -r -f $TOPDIR || fail "Could not remove $TOPDIR dir" )
mkdir $TOPDIR


########################################
# MSYS & other binary tools
#

# msys & stuff from the DD repo
#svn export $BINTOOL_SVN $TOPDIR/tools || fail "Svn failed to export from $BINTOOL_SVN"
[ -e DevDesktopCommon ] && rm -r -f DevDesktopCommon
git clone $BINTOOL_GIT  || fail "Git failed to get $BINTOOL_GIT"
mv DevDesktopCommon/bintools-win/msys $TOPDIR/tools
rm -r -f DevDesktopCommon

# mysql
MYSQL_ZIP=mysql-$MYSQL_VER.zip
MYSQL_URL=http://dev.mysql.com/get/Downloads/MySQL-5.5/$MYSQL_ZIP
if [ ! -e $MYSQL_ZIP ]; then
  wget $MYSQL_URL || fail "Could not download MySQL from $MYSQL_URL"
fi

unzip -o -j $MYSQL_ZIP mysql-$MYSQL_VER/bin/mysql.exe -d $TOPDIR/tools/bin
unzip -o -j $MYSQL_ZIP mysql-$MYSQL_VER/bin/mysqldump.exe -d $TOPDIR/tools/bin

########################################
# PHP

PHP_ZIP=php-$PHP_VER.zip
PHP_URL=http://windows.php.net/downloads/releases/$PHP_ZIP
if [ ! -e $PHP_ZIP ]; then
  wget $PHP_URL || fail "Could not download PHP from $PHP_URL"
fi

unzip $PHP_ZIP -d $TOPDIR/php

PHP_INI=$TOPDIR/php/php.ini

cp "$PHP_INI-development" "$PHP_INI"
replace_in_file '; extension_dir = "ext"' 'extension_dir = "ext"' "$PHP_INI"
enable_php_extension "bz2 curl fileinfo gd2 gettext intl mbstring mysql mysqli openssl pdo_mysql soap sockets tidy xmrpc xsl" "$PHP_INI"

########################################
# Drush, composer and setenv stuff

cd $TOPDIR
php -r "readfile('https://getcomposer.org/installer');" | php
./composer.phar require drush/drush:$DRUSH_VER || fail "Composer failed"
cd ..

cp assets/drush.bat $TOPDIR
cp assets/composer.bat $TOPDIR
cp assets/setenv.bat $TOPDIR
cp assets/setenv.js $TOPDIR
cp assets/notify_env_change.exe $TOPDIR/tools/bin


########################################
# Zip everything up

[ -e $TOPDIR.zip ] && rm $TOPDIR.zip
zip -r $TOPDIR.zip $TOPDIR
cd ..


echo "Done."
