#!/bin/bash
configure=""
debug="-d"
arch=""
dist="https://atom.io/download/atom-shell"
plat=`uname`
directory=""

if [ $plat == 'Linux' ] || [ $plat == 'Darwin' ]; then
  msvs=""
else
  msvs="--msvs_version=2013"
fi

while [[ $# > 0 ]]
do
key="$1"
case $key in
    # configure
    -c|--configure|configure)
    configure="configure"
    ;;

    #debug
    -r|--release|release)
    debug=""
    ;;

    -d|--debug|debug)
    debug="-d" # default
    ;;

    -t|--target|ELECTRON_VERSION)
    ELECTRON_VERSION="$2"
    shift
    ;;

    -D|--dist|--dist-url)
    dist="$2"
    shift
    ;;

    --msvs)
    msvs="$2"
    shift
    ;;

    #arch
    -x86|x86|-ia32|ia32)
    arch="--arch=ia32"
    ;;
    -x64|x64)
    arch="--arch=x64"
    ;;

    -a|--arch)
    arch="--arch=$2"
    shift
    ;;

    -d|--directory)
    directory="--directory=\"$2\""
    shift
    ;;

    # unknown option
    *) 
    echo "Unknown option: $i"
    exit 1
    ;;
esac
shift
done

if [ "$NPM_CONFIG_PREFIX" != "" ] && [ -f "${NPM_CONFIG_PREFIX}/node-gyp" ]; then
    # prefer globally installed node-gyp during "npm install"
    command=${NPM_CONFIG_PREFIX}/node-gyp
else
    command=`which node-gyp`
fi

# Get the version of electron if it wasn't specified.
if [ ! $ELECTRON_VERSION ]; then
    ELECTRON_VERSION=`./node_modules/.bin/elver`
fi

if [ ! $ELECTRON_VERSION ]; then
    # if we failed to get the latest version there may be a problem, report to user:
    echo ''
    echo 'Error: Failed to get valid electron version.'
    echo ''
    echo 'Please specify by one of the following methods:'
    echo '  command line arg:     --target $version'
    echo '  environment variable: export ELECTRON_VERSION=$version'
    echo '  add "engines": [ "electron": "<version>" ] to your package.json'
    echo '  ensure web access to: https://github.com/atom/electron/releases/latest'
    exit 1
fi

HOME=~/.electron-gyp "${command}" --target="${ELECTRON_VERSION}" ${msvs} ${arch} ${debug} ${directory} --dist-url=${dist} ${configure} build