#!/bin/bash

# Launchers to include in build: (space separated). An @ indicates envvars to set on Linux.
launchers="progvis.main@STORM_RENDER_BACKEND=gtk"

OUT_BASE=$STORM_ROOT/release/storm

arch="$1"
command="$2"
notes="$3"

if [[ $arch == *_win* ]]
then
    OUT_EXT=.zip
    add="7z a"
    exe=".exe"
    lib=".dll"
    scr=".bat"
else
    OUT_EXT=.tar
    add="tar -rf"
    exe=""
    lib=".so"
    scr=".sh"
fi
OUT=$OUT_BASE$OUT_EXT

# We only need the build command to know where to look for compiled files.
namesuffix=""
if [[ $command == *64* ]]
then
    namesuffix="64"
fi

# Figure out the GC used, we need it to find the executable.
if [[ $command == *mps* ]]
then
    gc=_mps
elif [[ $command == *smm* ]]
then
    gc=_smm
fi

function launcher {
    fn=${1%%@*}
    envvars=$(expr match "$1" '.*@\(.*\)')

    if [[ "$2" =~ \.bat$ ]]
    then
	echo '@"%~dp0Storm.exe" -f '"$fn" > "$2"
    else
	(
	    echo '#!/bin/bash'
	    echo 'DIR=$(dirname "$0")'
	    echo 'chmod +x "$DIR"/Storm'
	    while [ ! "x$envvars" == "x" ]
	    do
		echo "export ${envvars%%@*}"
		envvars=$(expr match "$envvars" '.*@\(.*\)')
	    done
	    echo "exec \"\$DIR\"/Storm -f $fn"
	) > "$2"
	chmod +x "$2"
    fi
}

function add_rename {
    cp $1 $2
    eval $add $OUT $2 > /dev/null
    rm $2
}

function add_rename_custom {
    cp $2 $3
    eval $add $1 $3 > /dev/null
    rm $3
}

if [[ -e $OUT ]]
then
    rm $OUT
fi

cd $STORM_ROOT

echo "Packing release..."

# Documentation.
find doc/ -type f | xargs --delimiter='\n' $add $OUT > /dev/null

# Release notes.
if [[ -f $notes ]]
then
    cp "$notes" doc/release_notes.md
else
    release-notes > doc/release_notes.md
fi

$add $OUT doc/release_notes.md > /dev/null
rm doc/release_notes.md

# Source code from root/
find root/ -type f -not -name "*$lib" | grep -v "server-tests/" | xargs --delimiter='\n' $add $OUT > /dev/null

# Rename and add dynamic libraries
IFS=$'\n'
for j in $(find root/ -name "Release${namesuffix}*${lib}")
do
    name=$(echo $j | sed "s/Release${namesuffix}//")
    # Otherwise Release64X.dll matches as 64X.dll when it should not.
    if [[ $name != */64* ]]
    then
	add_rename $j $name
    fi
done
# Mariadb library:
plainsuffix=32
if [[ $namesuffix != "" ]]
then
    plainsuffix=$namesuffix
fi
for j in $(find root/ -name "*_${plainsuffix}${lib}")
do
    name=${j%_${plainsuffix}${lib}}${lib}
    add_rename $j $name
done

# Add the Emacs plugin.
add_rename Plugin/emacs.el storm-mode.el


# Add any launchers.
for l in $launchers
do
    name=${l%%.*}$scr
    name=${name^} # upcase first letter
    launcher "$l" "$name"
    eval $add $OUT "$name" > /dev/null
    rm "$name"
done

# Add the main executable
add_rename_custom ${OUT} release${namesuffix}/Storm${gc}$exe Storm$exe

# Make it the proper name.
mv ${OUT} ${OUT_BASE}_${arch}${OUT_EXT}

if [[ $OUT_EXT == .tar ]]
then
    if [[ -e ${OUT_BASE}_$arch.tar.gz ]]
    then
	rm ${OUT_BASE}_$arch.tar.gz
    fi

    gzip ${OUT_BASE}_$arch.tar
fi

echo "Done!"
