#!/bin/bash

DEPLOY_SETTINGS=~/.kotlin-deploy-settings.xml

BUILD=$1
[ -z "$BUILD" ] && {
  echo "Usage: ./publish-maven-artifacts BUILD"
  echo "  where BUILD is like 0.1.XXXX"
  exit 1
}

[ ! -f "$DEPLOY_SETTINGS" ] && {
  echo "Maven deploy settings are not found at $DEPLOY_SETTINGS"
  exit 1
}

[ ! -f "update_dependencies.xml" -o ! -f "Kotlin.iml" ] && {
  echo "Run this script from Kotlin checkout root"
  exit 1
}

for cmd in java javac ant mvn git; do
  command -v $cmd >/dev/null 2>&1 || {
    echo "$cmd must available in \$PATH"
    exit 1
  }
done

(javac -version 2>&1 | fgrep -q 1.6.) || {
  echo "javac must report report 1.6.X version"
  exit 1
}

uncommitted=`git status --porcelain -uno`
[ -n "$uncommitted" ] && {
  echo "Uncommited changes detected, commit them and run this script again"
  echo "$uncommitted"
  exit 1
}

LOG=/tmp/kotlin-build-`date +%Y%m%d-%H%M%S`.log
echo "*** Writing build log to $LOG"

(
export MAVEN_OPTS="-Xms512m -Xmx1024M -XX:PermSize=256m -XX:MaxPermSize=512m"
export ANT_OPTS="-Xms512m -Xmx1024M -XX:PermSize=256m -XX:MaxPermSize=512m"

set -x -e

rm -rfv ~/.m2/repository/org/jetbrains/kotlin

rm -rf /tmp/kotlin-dependencies
git clean -f -d -x
git reset --hard

ant -f update_dependencies.xml
ant -f build.xml -Dbuild.number=$BUILD dist
cd libraries
mvn versions:set -DnewVersion=$BUILD
mvn package -PnoTest -DskipTests
find . -name target -type d -prune -print -exec rm -rf {} \;
mvn -s "$DEPLOY_SETTINGS" -PnoTest -DskipTests deploy
echo "*** Successfully uploaded version $BUILD to maven repository"
) 2>&1 | tee "$LOG"
