#!/bin/bash -e

if [[ "$#" -gt 2 || "$1" == "-h" ]]; then
    echo 'Create a Windows installer for OpenRCT2'
    echo ''
    echo 'Usage: create-installer [-i] [<destination>]'
    echo ''
    echo '    -i                    install portable NSIS'
    exit 1
fi

installnsis=
output=$1
if [[ "$1" == "-i" ]]; then
    installnsis=true
    output=$2
fi

basedir="$(readlink -f `dirname $0`/..)"
if [[ "$output" == "" ]]; then
    mkdir -p "$basedir/artifacts"
    output="$basedir/artifacts/openrct2-installer-$CONFIGURATION-$PLATFORM.exe"
fi

outputdir=$(dirname $output)
if ! [ -d "$outputdir" ]; then
    echo -e >&2 "\033[0;31m$outputdir does not exist\033[0m"
    exit 1
fi

output=$(cygpath -w $(readlink -f $output))

# Check makensis is available
if [[ "$installnsis" == "true" ]]; then
    $basedir/scripts/install-nsis -d /tmp/nsis
    export PATH=/tmp/nsis/bin:$PATH
fi

if ! [ -x "$(command -v makensis)" ]; then
    echo -e >&2 "\033[0;31mmakensis not found\033[0m"
    exit 1
fi

nsispath=$(cygpath -w $basedir/distribution/windows/install.nsi)
echo -e "\033[0;36mCreating installer for OpenRCT2 $OPENRCT2_VERSION-$OPENRCT2_VERSION_EXTRA ($PLATFORM)...\033[0m"
makensis "/DOUTFILE=$output" "//DAPPV_MAIN=$OPENRCT2_VERSION" "//DAPPV_EXTRA=${OPENRCT2_VERSION_EXTRA//\//\\}" "//DPLATFORM=$PLATFORM" "$nsispath"
printf '\033[0;32m%s\033[0m\n' "${output} created successfully"
