#!/bin/bash
set -x
if [ "$1"  != "" ] ; then
    repository=$1
    echo $repository 
fi

if [ "$2" != "" ]; then
    action=$2
fi

if [ "$3" != "" ]; then
    push_username=$3
fi

if [ "$4" != "" ]; then
    push_password=$4
fi

if [ "$action" = "build" -a "$action" = "sync" ] ; then
    exit 101
fi

if [ "$push_username" = "" ] ; then
    exit 102
fi

if [ "$push_password" = "" ] ; then
    exit 103
fi

if [ "$repository" = "" ] ; then
    exit 104
fi

ANT_OPTS="-Xmx512m"
export ANT_OPTS
HGMERGE=merge
export HGMERGE
/bin/pwd
rm -rf real.workspace
hg clone . real.workspace || exit 1
cd real.workspace

/bin/pwd

testmodule() {
    ant -f $1/build.xml test -Dtest-unit-sys-prop.ignore.random.failures=true
}

if [ "$action" = "build" ]; then
    hg pull http://hg.netbeans.org/$repository || exit 1
    hg up -C http://hg.netbeans.org/$repository || exit 1

    ant build || exit 2
    ant commit-validation # || exit 3
#    testmodule openide.util  || exit 4
#    testmodule openide.modules || exit 4
#    testmodule openide.filesystems || exit 4
# masterfs is currently broken, Radek wants me to disable it until 6.1M2:
#    ant -f masterfs|| exit 4
#    testmodule openide.nodes|| exit 4
#    testmodule openide.options || exit 4
#    testmodule openide.dialogs || exit 4
#    testmodule openide.awt || exit 4
#    testmodule openide.windows || exit 4
#    testmodule core.startup # || exit 4
#    testmodule openide.io || exit 4
#    if [ `hg out --template '{node|short}\n' http://hg.netbeans.org/$repository | wc -l` > 0 ]; then
#        echo No outgoing changes
#        exit 0
#    fi

#    for i in 1 2 3; do
#       hg pull http://hg.netbeans.org/$repository || exit 5
#       if [ `hg heads --template '{node|short}\n' | wc -l` = 1 ]
#       then
#           hg up || exit 6
#       else
#           hg merge || exit 7
#           hg ci -m 'Automated merge' || exit 8
#       fi
#       hg out http://hg.netbeans.org/main
#       hg in http://hg.netbeans.org/main
#       hg push https://"$push_username":"$push_password"@hg.netbeans.org/main && exit 0
#    done
#    exit 5
    exit 0
fi

if [ "$action" = "sync" ]; then
    # update the latest tip of the private repository
    hg fetch http://hg.netbeans.org/$repository

    # pulling new changes from main-golden
    # not needed because the real.workspace is the latest main-golden
    # hg fetch http://hg.netbeans.org/main-golden

    # Now build and run tests before push
    ant build || exit 2
    ant commit-validation # || exit 3

    # Just make sure that there are no new changes before push
    hg out http://hg.netbeans.org/$repository
    hg fetch http://hg.netbeans.org/$repository

    hg push https://"$push_username":"$push_password"@hg.netbeans.org/$repository

    # Now push to the test repo
    # echo "Also for now push to testpush-repo:"
    # hg fetch ../../testpush-repo
    # hg push ../../testpush-repo
    exit 0
fi
# Something wrong here
exit 1
