#!/bin/sh

# Copyright (c) 2015 Electric Cloud, Inc.
# All rights reserved

# This script builds psxemake.exe with the local installation of Cygwin
# and copies selected results into your ElectricAccelerator installation
# tree.  This script assumes that it is located within that tree.

set -e

# Normalize the environment, so that variables intended
# for user builds do not affect this installation build.

export PATH=/bin:/usr/bin
unset LD_LIBRARY_PATH
unset LD
unset CC
unset DEBUG

usage()
{
    echo "Usage: $0 [--largestack] [--version <major.minor.patch>]" >&2
    echo "When updating an agent installation, use both arguments." >&2
}

# Parse command line options.

largestack=""
version=""
while test $# -ne 0
do
    case "$1" in
        -h|--help)
            usage
            exit 0
            ;;
        --largestack)
            largestack="_largestack"
            ;;
        --version)
            shift
            version="$1"
            ;;
        *)
            echo "$0: unrecognized option: '$1'" >&2
            usage
            exit 2
            ;;
    esac
    shift
done

# Check whether the Cygwin installation
# includes the necessary tools.

missing=0

for tool in gcc make peflags
do
    if test ! -e "`which \"$tool\"`"
    then
        echo "not found: '$tool'" >&2
        missing=1
    fi
done

for lib in iconv
do
    lib="/usr/lib/lib$lib.dll.a"
    if test ! -e "$lib"
    then
        echo "not found: '$lib'" >&2
        missing=1
    fi
done

if test $missing -eq 1
then
    exit 1
fi

# Compute the target pathname relative to the location of this script.

bin="`dirname \"$0\"`"
arch32="$bin/.."
versioned_bin="$arch32/$version/bin"

if test _"`uname -m`" = _"x86_64"
then
    bin="$arch32/64/bin"
    versioned_bin="$arch32/$version/64/bin"
fi

# Ensure that we clean up temporary files even when interrupted.

target="$bin/psxemake.exe"
target_tmp="$target.tmp.$$"

versioned_target="$versioned_bin/psxemake.exe"
versioned_target_tmp="$versioned_target.tmp.$$"

tmp="/tmp/`basename $0`.$$"
trap 'rm -rf "$tmp" "$target_tmp" "$versioned_target_tmp"' \
    EXIT HUP INT TERM QUIT

# Build.

export ARCHDIR="$tmp/arch"
export NEUTDIR="$tmp/neut"

noisy() {
    echo "$@"
    "$@"
}

noisy make -C "$arch32/vrpsx"

# Backup any executable that would be replaced,
# unless doing so would replace an earlier backup.

if test -e "$target" -a ! -e "$target.original"
then
    noisy mv "$target" "$target.original"
fi

# Copy executable to target pathname.

noisy cp "$ARCHDIR/direct/vrpsx_loader$largestack.exe" "$target_tmp"
noisy mv "$target_tmp" "$target"

if test "_$version" != "_"
then
    # Copy it to the version-specific directory as well.

    noisy cp "$target" "$versioned_target_tmp"
    noisy mv "$versioned_target_tmp" "$versioned_target"
fi
