#!/bin/sh
# usage forge-remoted [-e environment] [-s script]

PRODUCT_NAME="Linaro Forge"

# Follow symlinks to get the canonical path of this script (in case user has symlinked it to somewhere outside the install directory).
if type readlink >/dev/null 2>&1; then
	CANONICAL_EXE="`readlink -f "$0"`"
else
	CANONICAL_EXE="$0"
fi

# Set FORGE_TOOLS_PATH to the parent of this script's directory.
FORGE_TOOLS_PATH="$(cd "$(dirname "$CANONICAL_EXE")/.."; pwd)"
. $FORGE_TOOLS_PATH/libexec/common

# ARGUMENTS
FORWARDED_ENVIRONMENT=
USER_SCRIPT=

while getopts "e:s:" OPTION
do
    case $OPTION in
        e)
            FORWARDED_ENVIRONMENT=$OPTARG
            ;;
        s)
            USER_SCRIPT=$OPTARG
            ;;
        ?)
            ;;
    esac
done

# getopts above will not modify "$@", but arguments between forge-remoted and
# forge-remoted.bin are separated by --, so only forward arguments to forge-remoted.bin
# to the right of --
while [ $# -gt 0 ]; do
    if [ "$1" = "--" ]; then
        shift
        break
    fi
    shift
done

SITE_SCRIPT="$FORGE_TOOLS_PATH/remote-init" # Sourced by all connections using this installation
USER_WIDE_SCRIPT="${FORGE_CONFIG_DIR:-$HOME/.allinea}/remote-init" # Sourced by all connections for this user

# source a site-wide script
if [ -r "$SITE_SCRIPT" ]; then
    . "$SITE_SCRIPT"
fi

# source user-wide script
if [ -r "$USER_WIDE_SCRIPT" ]; then
    . "$USER_WIDE_SCRIPT"
fi

# source a user script if provided
if [ -r "$USER_SCRIPT" ]; then
    . "$USER_SCRIPT"
fi

export SSH_ASKPASS="$FORGE_TOOLS_PATH/libexec/remote-askpass"

# start daemon
if [ -n "${FORWARDED_ENVIRONMENT}" ]; then
    eval "export $FORWARDED_ENVIRONMENT"
fi

"$FORGE_TOOLS_PATH/libexec/findarch" "libexec/forge-remoted.bin" "$@"
