#! /bin/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.
#

XCODE_VER=$(xcodebuild -version | head -n 1 | sed -e 's/Xcode //')
XCODE_MIN_VERSION="4.5"

if [[ "$XCODE_VER" < "$XCODE_MIN_VERSION" ]]; then
	echo "Cordova can only run in Xcode version $XCODE_MIN_VERSION or greater."
	exit 1
fi

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

APP_PATH=${1:-$PROJECT_PATH/build/$PROJECT_NAME.app}
DEVICE_FAMILY=${2:-${DEVICE_FAMILY:-iphone}}

if [ ! -d "$APP_PATH" ]; then
	echo "Project '$APP_PATH' is not built. Building."
    $CORDOVA_PATH/build || exit $?
fi

if [ ! -d "$APP_PATH" ]; then
	echo "$APP_PATH not found to emulate."
	exit 1
fi

IOS_SIM_MIN_VERSION="1.5"
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 'brew install ios-sim' using homebrew: http://mxcl.github.com/homebrew/\033[m"; exit 1;
	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."
	exit 1
fi

# launch using ios-sim
ios-sim launch "$APP_PATH" --family "$DEVICE_FAMILY" --stderr "$CORDOVA_PATH/console.log" --stdout "$CORDOVA_PATH/console.log" &

