# -v print lines as they are read
# -x print lines as they are executed
# -e abort script at first error
set -e

_plugin=($(echo $CI_BUILD_REPO | tr '/' ' '))

ADDITIONAL_PLUGINS=($(echo $ADDITIONAL_PLUGINS))
REDMINE_ROOT=$CI_PROJECT_DIR/.redmine
PLUGINS_ROOT=$REDMINE_ROOT/plugins
CURRENT_PLUGIN=${_plugin[-1]/.git/}
CURRENT_PLUGIN_ROOT=$PLUGINS_ROOT/$CURRENT_PLUGIN


echo "--> REDMINE_REPO: $REDMINE_REPO"
echo "--> REDMINE_ROOT: $REDMINE_ROOT"
echo "--> CURRENT_PLUGIN: $CURRENT_PLUGIN"
echo "--> ADDITIONAL_PLUGINS: $ADDITIONAL_PLUGINS"


# Setup redmine
git clone ssh://git@git.easy.cz/$REDMINE_REPO.git $REDMINE_ROOT


# Init database
ruby -ryaml -rsecurerandom -e "
  config = {
    'adapter' => 'mysql2',
    'database' => 'redmine_test_'+SecureRandom.hex(8).to_s,
    'host' => '127.0.0.1',
    'username' => 'root',
    'password' => ENV['MYSQL_PASS'],
    'encoding' => 'utf8'
  }
  config = { 'test' => config, 'development' => config }.to_yaml
  File.write('.redmine/config/database.yml', config)
"


# Init current plugin
[ -d $CURRENT_PLUGIN_ROOT ] && rm -rf $CURRENT_PLUGIN_ROOT
ln -s $CI_PROJECT_DIR $CURRENT_PLUGIN_ROOT


# Init other plugins
cd $PLUGINS_ROOT
for plugin in ${ADDITIONAL_PLUGINS[*]}
do
  echo "--> Init plugin: $plugin"

  [ -d $plugin ] && rm -rf $plugin
  git clone -b devel ssh://git@git.easy.cz/redmine/$plugin.git $plugin

  pushd $plugin

  # Checkout to the same branch if exist
  if [[ $(git branch --list $CI_BUILD_REF_NAME) ]]
  then
    echo "--> Checkout $CI_BUILD_REF_NAME"
    git checkout $CI_BUILD_REF_NAME
    git pull
  fi

  popd
done


# Run tests
cd $REDMINE_ROOT

to_test="{$(echo ${ADDITIONAL_PLUGINS[*]} $CURRENT_PLUGIN | tr ' ' ',')}"

bundle update
bundle exec rake db:drop db:create db:migrate
bundle exec rake easyproject:install
bundle exec rake test:prepare RAILS_ENV=test
bundle exec rake easyproject:tests:spec NAME=$to_test RAILS_ENV=test
bundle exec rake db:drop
