#!bash -lex
#
# build-vm.sh -- Builds Cog Virtual Machine. Have to be used together with Jenkins.
#
# Copyright (c) 2012 Christophe Demarey
#

#http://files.pharo.org/vm/src/cog.tar.gz
#http://files.pharo.org/vm/src/vmmaker-image.zip

# Set environment
PROCESS_PLUGIN="UnixOSProcessPlugin"
ZIP_FILTER='*'
SQUEAKVM="/root/smalltalk_dists/pharo2.0/bin/pharo"


if [ "$OS" == "" ]; then
	OS="linux"
fi


if [ "$OS" == "win" ]; then
    set -e # Stop the execution if a command fails!
	CONFIGNAME="CogWindowsConfig"
    PROCESS_PLUGIN="Win32OSProcessPlugin"
    ZIP_FILTER=' *.exe *.dll'
elif [ "$OS" == "mac" ]; then
    CONFIGNAME="CogCocoaIOSConfig"
    export MACOSX_DEPLOYMENT_TARGET=10.5
elif [ "$OS" == "linux" ]; then
    CONFIGNAME="CogUnixConfig"
fi


echo "===Compile OS target :: $OS"

# Unpack sources
echo "===unpack platform source"
cd "$WORKSPACE"

rm -rf cog
tar xzf cog.tar.gz || echo # echo needed for Windows build (error on symlinks creation)

mkdir -p cog/build
mkdir -p cog/image

echo "===unpack smalltalk image for vmmkaer"
cd cog/image
unzip -o ../../vmmaker-image.zip


# Generate sources
echo "===Genarate vmmaker source from image"
echo "$CONFIGNAME new
  addExternalPlugins: #( FT2Plugin );
  addInternalPlugins: #( $PROCESS_PLUGIN );
  generateSources; generate.

Smalltalk snapshot: false andQuit: true." > ./script.st
"$SQUEAKVM" -headless generator.image script.st -headless

echo "process break here!"

# exit ## want debug step then uncomment. add by onion

echo "===pack vmmaker source"
cd ../../
tar -czf ${CONFIGNAME}-sources.tar.gz -C cog .


# Compile
echo "===start compile CogVM"
cd cog/build
if [ "$OS" == "win" ]; then
  cmake -G "MSYS Makefiles" .
else
  cmake .
fi
make
cd ../results

# Archive
echo "===pack CogVM"
COG_ZIP_FILE="Cog-${OS}.zip"

zip -r $COG_ZIP_FILE $ZIP_FILTER
mv -f $COG_ZIP_FILE ../../

#if [ "$OS" == "mac" ]; then
#    zip -r ../build/CogVM.zip CogVM.app
#    mv -f ../build/CogVM.zip ../../
#else
#    zip -r Cog.zip $ZIP_FILTER
#    mv Cog.zip ../../
#fi

# success
echo "===all process finished! Conguration!"
exit 0
