#! /bin/sh
#       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.
#
# create a cordova/android project
# 
# USAGE
#   ./create [path appname]
#
set -e

if [ -n "$1" ] && [ "$1" == "-h" ]
then
    echo 'usage: create path appname'
    echo 'After you have created your application, make sure to customize the project.properties file inside your app directory with your environment specifics!'
    exit 0
fi

BUILD_PATH=$( cd "$( dirname "$0" )/.." && pwd )
VERSION=$(cat $BUILD_PATH/VERSION)

PROJECT_PATH=${1:-"./example"}
APPNAME=${2:-"cordovaExample"}

# clobber any existing example
if [ -d $PROJECT_PATH ]
then
    echo "Project already exists! Delete and recreate"
    exit 1
fi

# cleanup after exit and/or on error
function on_exit {
    echo "Cleaning up ..."
    [ -d $BUILD_PATH/build ] && rm -rf $BUILD_PATH/build
    [ -d $BUILD_PATH/dist ] && rm -rf $BUILD_PATH/dist
    echo "Remember to update the project.properties file inside your application directory!"
}

function on_error {
    echo "An error occured. Deleting project..."
    [ -d $PROJECT_PATH ] && rm -rf $PROJECT_PATH
}

# we do not want the script to silently fail
trap on_error ERR
trap on_exit EXIT

ANT=$(which ant)

MANIFEST_PATH=$PROJECT_PATH/www/config.xml

# compile cordova.js and cordova.jar if in source, ignore if in distribution
if [ ! -e $BUILD_PATH/www/ext/cordova-$VERSION.jar ] && [ -d $BUILD_PATH/framework ]
then
	echo "Building cordova-$VERSION.jar and cordova-$VERSION.js ..."
	(cd $BUILD_PATH && $ANT dist &> /dev/null )
	
	# copy project template
	echo "Copying assets and resources ..."
	cp -r $BUILD_PATH/dist/sample/. $PROJECT_PATH
else
	# copy project template if in distribution
	echo "Copying assets and resources ..."
	cp -r $BUILD_PATH/sample/. $PROJECT_PATH
fi

# interpolate the app name into config.xml
echo "Updating config.xml ..."
sed -i '' -e "s/__NAME__/${APPNAME}/g" $MANIFEST_PATH