#!/usr/bin/env bash
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#  KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
# Valid values for "--target" (case sensitive):
#   iPhone-4s
#   iPhone-5
#   iPhone-5s
#   iPhone-6-Plus
#   iPhone-6
#   iPad-2
#   iPad-Retina
#   iPad-Air
#   Resizable-iPhone
#   Resizable-iPad


OPTION_RESULT=()
TARGET="iPhone-6"

# multi-device flow default
USE_DEVICE=true
USE_SIMULATOR=false

# separates "key=value", sets an array with 0th index as key, 1st index as value
_parseOption()
{
    local ARG=$@
    OIFS=$IFS
    IFS='='

    OPTION_RESULT=()
    for i in ${ARG[@]}
    do
      OPTION_RESULT+=($i)
    done

    IFS=$OIFS
}

# parses key=value arguments
_parseArgs()
{
  for arg in "$@"
  do
    _parseOption ${arg}
    case "${OPTION_RESULT[0]}" in
      "--target")
        TARGET=${OPTION_RESULT[1]}
        ;;
    "--device")
      USE_DEVICE=true
      USE_SIMULATOR=false
      ;;
    "--emulator")
      USE_DEVICE=false
      USE_SIMULATOR=true
      ;;
    esac
  done
}

_parseArgs "$@"

CORDOVA_PATH=$( cd "$( dirname "$0" )" && pwd -P)
PROJECT_PATH="$(dirname "$CORDOVA_PATH")"
XCODEPROJ=$( ls "$PROJECT_PATH" | grep .xcodeproj  )
PROJECT_NAME=$(basename "$XCODEPROJ" .xcodeproj)

SIMULATOR_APP_PATH="$PROJECT_PATH/build/emulator/$PROJECT_NAME.app"
DEVICE_APP_PATH="$PROJECT_PATH/build/device/$PROJECT_NAME.app"

source "$CORDOVA_PATH/check_reqs"


# if device build found, run it first
if "$USE_DEVICE"; then
    IOS_DEPLOY_MIN_VERSION="1.2.0"
    IOS_DEPLOY_LOCATION=$(which ios-deploy)
    if [ $? != 0 ]; then
        echo -e "\033[31mError: ios-deploy was not found. Please download, build and install version $IOS_DEPLOY_MIN_VERSION or greater from https://github.com/phonegap/ios-deploy into your path. Or 'npm install -g ios-deploy' using node.js: http://nodejs.org/\033[m" 1>&2;
    	exit 1
    fi

    IOS_DEPLOY_VERSION=$(ios-deploy --version)
    if [[ "$IOS_DEPLOY_VERSION" < "$IOS_DEPLOY_MIN_VERSION" ]]; then
    	echo "Cordova needs ios-deploy version $IOS_DEPLOY_MIN_VERSION or greater, you have version $IOS_DEPLOY_VERSION." 1>&2;
    	exit 1
    fi
    
    DEVICE_CONNECTED=$(ios-deploy -c)
    if [ $? != 0 ]; then
    	echo "No device is connected, trying Simulator." 1>&2;
        USE_SIMULATOR=true
    else
        # if we got here, we can deploy the app, then exit success
        "$CORDOVA_PATH/build" --device || exit $?
        ios-deploy -d -b "$DEVICE_APP_PATH"
    	exit 0
    fi
fi

if "$USE_SIMULATOR"; then
    IOS_SIM_MIN_VERSION="3.0"
    IOS_SIM_LOCATION=$(which ios-sim)
    if [ $? != 0 ]; then
        echo -e "\033[31mError: ios-sim was not found. Please download, build and install version $IOS_SIM_MIN_VERSION or greater from https://github.com/phonegap/ios-sim into your path. Or 'npm install -g ios-sim' using node.js: http://nodejs.org/\033[m" 1>&2;
    	exit 1
    fi

    IOS_SIM_VERSION=$(ios-sim --version)

    if [[ "$IOS_SIM_VERSION" < "$IOS_SIM_MIN_VERSION" ]]; then
    	echo "Cordova needs ios-sim version $IOS_SIM_MIN_VERSION or greater, you have version $IOS_SIM_VERSION." 1>&2;
    	exit 1
    fi
    
    # launch using ios-sim
    "$CORDOVA_PATH/build" --emulator || exit $?
    ios-sim launch "$SIMULATOR_APP_PATH" --stderr "$CORDOVA_PATH/console.log" --stdout "$CORDOVA_PATH/console.log" --devicetypeid com.apple.CoreSimulator.SimDeviceType.$TARGET --exit
fi

