#! /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 package activity]
#
set -e

PROJECT_PATH=${1:-"./example"}
PACKAGE=${2:-"org.apache.cordova.example"}
ACTIVITY=${3:-"cordovaExample"}
TARGET=$(android list targets | grep 'id: ' | sed 's/id: \([0-9]*\).*/\1/g' | tail -1)
VERSION=$(cat ./VERSION)

# clobber any existing example
if [ $# -eq 0 ]
then
    rm -rf $PROJECT_PATH
fi

# update the cordova-android framework for the desired target
android update project --target $TARGET --path ./framework

if [ ! -e ./framework/libs/commons-codec-1.6.jar ]; then
    # Use curl to get the jar (TODO: Support Apache Mirrors)
    curl -OL http://mirror.symnds.com/software/Apache//commons/codec/binaries/commons-codec-1.6-bin.zip
    unzip commons-codec-1.6-bin.zip
    mkdir -p ./framework/libs
    cp commons-codec-1.6/commons-codec-1.6.jar ./framework/libs/
fi

# compile cordova.js and cordova.jar
cd ./framework && ant jar && cd ../

# copy all the bin scripts etc in there
cp -R ./bin/templates/project/ $PROJECT_PATH

# copy in cordova.js
cp ./framework/assets/www/cordova-$VERSION.js $PROJECT_PATH/.cordova/android/cordova-$VERSION.js

# copy in cordova.jar
cp ./framework/cordova-$VERSION.jar $PROJECT_PATH/.cordova/android/cordova-$VERSION.jar

# copy in res/xml
cp ./framework/res/xml/cordova.xml $PROJECT_PATH/.cordova/android/cordova.xml
cp ./framework/res/xml/plugins.xml $PROJECT_PATH/.cordova/android/plugins.xml

# app properties
cat > $PROJECT_PATH/.cordova/config <<eom
VERSION=$VERSION
PROJECT_PATH=$PROJECT_PATH
PACKAGE=$PACKAGE
ACTIVITY=$ACTIVITY
TARGET=$TARGET
eom

(cd $PROJECT_PATH && ./cordova/create)