#!/bin/bash

OPTIND=1
TOP_DIR=$(pwd)

# Define default options.
PACKAGE="standard"
ACTION="build"
SOURCE="false"
VERSION=""
CONCURRENCY=8

# Read command line options.
while getopts ":h?fusv:c:" opt; do
  case "$opt" in
    h|\?)
      echo "Usage: `basename $0` [-h] [-f] [-u] [-s] [-v version] [-c concurrency]"
      exit 1
      ;;
    f)
      PACKAGE="full"
      ;;
    u)
      ACTION="upgrade"
      ;;
    s)
      SOURCE=true
      ;;
    v)
      VERSION="?h=$OPTARG"
      ;;
    c)
      CONCURRENCY=$OPTARG
      ;;
  esac
done

# Global Settings
# ===============

MAKE_OPTIONS="--concurrency=$CONCURRENCY --contrib-destination=profiles/drustack --no-cache --force-complete"
MAKE_FILE="http://cgit.drupalcode.org/drustack/plain/makes/$PACKAGE.make$VERSION"
MAKE_PATH="."


# Global Functions
# ================

function pre_build()
{
    if [[ $ACTION == 'build' ]]; then
        MAKE_OPTIONS="$MAKE_OPTIONS --prepare-install"
    fi
}

function pre_upgrade()
{
    if [[ $ACTION == 'upgrade' ]]; then
        chmod a+w sites/*
        rm -rf profiles/drustack
    fi
}

function pre_source()
{
    if [[ "$SOURCE" == true ]]; then
        MAKE_OPTIONS="$MAKE_OPTIONS --no-gitinfofile --working-copy"
    fi
}

function post_upgrade()
{
    if [[ $ACTION == 'upgrade' ]]; then
        chmod a-w sites/*
    fi
}

function post_package()
{
    if [[ "$SOURCE" == false ]]; then
        rm -rf profiles/drustack/.gitignore

        find profiles/drustack/*/contrib/ -type f -name '*.info' |
        xargs grep -l 'project = "drustack"' |
        while read DATA; do
            TMP=`mktemp`
            head -n -6 $DATA > $TMP
            mv $TMP $DATA
        done
    fi
}

function post_source()
{
    if [[ "$SOURCE" == true ]]; then
        find $TOP_DIR -type d -name '.git' |
        while read DATA; do
            PROJECT=`echo $DATA | sed "s/^.*\/\([^\/]*\)\/\.git/\1/g"`
            cd $DATA/../
            git remote set-url --push origin `whoami`@git.drupal.org:project/$PROJECT.git
            git fetch
            git status
            git remote -v
        done
    fi
}


# Install Packages
# ================

set -o xtrace

cd $TOP_DIR

pre_build
pre_upgrade

#pre_package
pre_source

drush -y make $MAKE_OPTIONS $MAKE_FILE $MAKE_PATH

#post_build
post_upgrade

post_package
post_source
