#!/bin/sh

if [ "x$1" = "x" ]; then
    # No arguments
    echo Please provide one argument,e.g : $0 2.0
    exit 1;
fi

if [ "x$2" != "x" ]; then
    # If this is a meta-package being built, we should aim for installation in /Applications...
    # For the actual mcstas part, the packages need a 'deep' PREFIX
    export MCINSTALL_PREFIX=/Applications/McStas-$1.app/Contents/Resources/
fi

# 64-bit Mac OS
./mkdist mcstas $1 "" "" mac_SL "" -- OSXpkg
./mkdist mcstas-comps $1 "" "" mac_SL "" -- OSXpkg
./mkdist mcstas-tools-perl $1 tools/Legacy-Perl/ "" mac_SL "" -- OSXpkg
./mkdist mcstas-tools-python-mcplot-chaco $1 tools/Python/mcplot/chaco/ "" mac_SL "" -- OSXpkg
./mkdist mcstas-tools-python-mcplot-matplotlib $1 tools/Python/mcplot/matplotlib/ "" mac_SL "" -- OSXpkg
./mkdist mcstas-tools-matlab-mcplot $1 tools/matlab/mcplot/ "" mac_SL "" -- OSXpkg
./mkdist mcstas-tools-python-mcrun $1 tools/Python/mcrun/ "" mac_SL "" -- OSXpkg
./mkdist mcstas-tools-python-mcgui $1 tools/Python/mcgui/ "" mac_SL "" -- OSXpkg
./mkdist mcstas-tools-python-mcdisplay $1 tools/Python/mcdisplay/x3d/ "" mac_SL "" -- OSXpkg
./mkdist mcstas-tools-python-mcdisplay-r $1 tools/Python/mcdisplay/R/ "" mac_SL "" -- OSXpkg
./mkdist mcstas-tools-python-mcdisplay-matplotlib $1 tools/Python/mcdisplay/matplotlib/ "" mac_SL "" -- OSXpkg
./mkdist mcstas-tools-python-mcdisplay-vtk $1 tools/Python/mcdisplay/VTK/ "" mac_SL "" -- OSXpkg
./mkdist mcstas-manuals $1 doc/manuals/mcstas/ "" mac_SL "o" -- OSXpkg

if [ "x$2" != "x" ]; then
    # If this is a meta-package being built, we should aim for installation in /opt/mccode
    export MCINSTALL_PREFIX=/usr/local/
fi
#./mkdist mcstas-gcc $1 support/MacOSX/gcc-hpc/10.8 "" mac_SL "" -- OSXpkg
#./mkdist mcstas-openmpi $1 support/MacOSX/openmpi/10.8 "" mac_SL "" -- OSXpkg

if [ "x$2" != "x" ]; then
    # Build the App bundle and meta-package also.
    # The App needs a higher-level PREFIX
    export MCINSTALL_PREFIX=/Applications/McStas-$1.app/
    ./mkdist mcstas-app $1 support/MacOSX/McCode.app/ "" mac_SL "" -- OSXpkg

    OSXVER=`sw_vers -productVersion|cut -f -2 -d.|sed -e 's/\./\_/g'`
    
    cd dist
    DISTDIR=$PWD
    unzip ../support/MacOSX/Perl-Tk/Tk-*${OSXVER}*zip
    unzip ../support/MacOSX/SciPDL/SciKarl-Intel-v0.12.pkg
    cd -
    # A hack for creating a metapackage
    cp -rp meta-pkgs/OSX/McStas-Metapackage_10_6.pmdoc dist/McStas-Metapackage.pmdoc
    cp -rp meta-pkgs/OSX/mcstas_logos_etc dist/logos_etc
    cd dist/McStas-Metapackage.pmdoc    

    REGEX="s/@VERSION@/${1}/g"
    REGEXDIR="s+@DISTDIR@+${DISTDIR}+g"
    
    find . -name \*xml -exec sed -i\.bak $REGEX \{\} \;
    find . -name \*xml -exec sed -i\.bak2 $REGEXDIR \{\} \;
    rm *.bak
    rm *.bak2
    cd ..
    open McStas-Metapackage.pmdoc
fi
