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

if [ -z "$1" ] || [ "$1" == "-h" ]
then
    echo "Usage: $0 <path_to_new_project> <package_name> <project_name>"
    echo "Make sure the Android SDK tools folder is in your PATH!"
    echo "    <path_to_new_project>: Path to your new Cordova iOS project"
    echo "    <package_name>: Package name, following reverse-domain style convention"
    echo "    <project_name>: Project name"
    exit 0
fi

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

PROJECT_PATH="${1:-'./example'}"
PACKAGE=${2:-"org.apache.cordova.example"}
ACTIVITY=$(echo ${3:-"cordovaExample"} | tr -d '[:blank:][:punct:]')
APP_LABEL=${3:-"Cordova Example"};

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

function createAppInfoJar {
    pushd "$BUILD_PATH"/bin/templates/cordova/ApplicationInfo > /dev/null
    javac ApplicationInfo.java
    jar -cfe ../appinfo.jar ApplicationInfo ApplicationInfo.class
    popd > /dev/null
}

function on_error {
    echo "An unexpected error occurred: $previous_command exited with $?"
    echo "Deleting project..."
    [ -d "$PROJECT_PATH" ] && rm -rf "$PROJECT_PATH"
    exit 1
}

function replace {
    local pattern=$1
    local filename=$2
    # Mac OS X requires -i argument
    if [[ "$OSTYPE" =~ "darwin" ]]
    then
        /usr/bin/sed -i '' -e "$pattern" "$filename"
    elif [[ "$OSTYPE" =~ "linux" ]]
    then
        /bin/sed -i -e $pattern "$filename"
    fi
}

# we do not want the script to silently fail
trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG
trap on_error ERR

ANDROID_BIN="${ANDROID_BIN:=$( which android )}"
PACKAGE_AS_PATH=$(echo $PACKAGE | sed 's/\./\//g')
ACTIVITY_PATH="$PROJECT_PATH"/src/$PACKAGE_AS_PATH/$ACTIVITY.java
MANIFEST_PATH="$PROJECT_PATH"/AndroidManifest.xml
STRINGS_PATH="$PROJECT_PATH"/res/values/strings.xml

TARGET=$("$ANDROID_BIN" list targets | grep id: | tail -1 | cut -f 2 -d ' ' )
API_LEVEL=$("$ANDROID_BIN" list target | grep "API level:" | tail -n 1 | cut -f 2 -d ':' | tr -d ' ')

# check that build targets exist
if [ -z "$TARGET" ] || [ -z "$API_LEVEL" ]
then
    echo "No Android Targets are installed. Please install at least one via the android SDK"
    exit 1
fi

# if this a distribution release no need to build a jar
if [ ! -e "$BUILD_PATH"/cordova-$VERSION.jar ] && [ -d "$BUILD_PATH"/framework ]
then
    # update the cordova-android framework for the desired target
    "$ANDROID_BIN" update project --target $TARGET --path "$BUILD_PATH"/framework &> /dev/null

    # compile cordova.js and cordova.jar
    pushd "$BUILD_PATH"/framework > /dev/null
    ant jar > /dev/null
    popd > /dev/null
fi

# create new android project
"$ANDROID_BIN" create project --target $TARGET --path "$PROJECT_PATH" --package $PACKAGE --activity $ACTIVITY &> /dev/null

# copy project template
cp -r "$BUILD_PATH"/bin/templates/project/assets "$PROJECT_PATH"
cp -r "$BUILD_PATH"/bin/templates/project/res "$PROJECT_PATH"

# copy cordova.js, cordova.jar and res/xml
if [ -d "$BUILD_PATH"/framework ]
then
    cp -r "$BUILD_PATH"/framework/res/xml "$PROJECT_PATH"/res
    cp "$BUILD_PATH"/framework/assets/www/cordova.js "$PROJECT_PATH"/assets/www/cordova.js
    cp "$BUILD_PATH"/framework/cordova-$VERSION.jar "$PROJECT_PATH"/libs/cordova-$VERSION.jar
else
    cp -r "$BUILD_PATH"/xml "$PROJECT_PATH"/res/xml
    cp "$BUILD_PATH"/cordova.js "$PROJECT_PATH"/assets/www/cordova.js
    cp "$BUILD_PATH"/cordova-$VERSION.jar "$PROJECT_PATH"/libs/cordova-$VERSION.jar
fi

# interpolate the activity name and package
cp "$BUILD_PATH"/bin/templates/project/Activity.java "$ACTIVITY_PATH"
replace "s/__ACTIVITY__/${ACTIVITY}/g" "$ACTIVITY_PATH"
replace "s/__ID__/${PACKAGE}/g" "$ACTIVITY_PATH"

# interpolate the app name into strings.xml
replace "s/>${ACTIVITY}</>${APP_LABEL}</g" "$STRINGS_PATH"

cp "$BUILD_PATH"/bin/templates/project/AndroidManifest.xml "$MANIFEST_PATH"
replace "s/__ACTIVITY__/${ACTIVITY}/g" "$MANIFEST_PATH"
replace "s/__PACKAGE__/${PACKAGE}/g" "$MANIFEST_PATH"
replace "s/__APILEVEL__/${API_LEVEL}/g" "$MANIFEST_PATH"

# creating cordova folder and copying run/build/log/launch scripts
mkdir "$PROJECT_PATH"/cordova
mkdir "$PROJECT_PATH"/cordova/lib
createAppInfoJar
cp "$BUILD_PATH"/bin/templates/cordova/appinfo.jar "$PROJECT_PATH"/cordova/appinfo.jar
cp "$BUILD_PATH"/bin/templates/cordova/build "$PROJECT_PATH"/cordova/build
cp "$BUILD_PATH"/bin/templates/cordova/clean "$PROJECT_PATH"/cordova/clean
cp "$BUILD_PATH"/bin/templates/cordova/log "$PROJECT_PATH"/cordova/log
cp "$BUILD_PATH"/bin/templates/cordova/run "$PROJECT_PATH"/cordova/run
cp "$BUILD_PATH"/bin/templates/cordova/version "$PROJECT_PATH"/cordova/version
cp "$BUILD_PATH"/bin/templates/cordova/lib/install-device "$PROJECT_PATH"/cordova/lib/install-device
cp "$BUILD_PATH"/bin/templates/cordova/lib/install-emulator "$PROJECT_PATH"/cordova/lib/install-emulator
cp "$BUILD_PATH"/bin/templates/cordova/lib/list-devices "$PROJECT_PATH"/cordova/lib/list-devices
cp "$BUILD_PATH"/bin/templates/cordova/lib/list-emulator-images "$PROJECT_PATH"/cordova/lib/list-emulator-images
cp "$BUILD_PATH"/bin/templates/cordova/lib/list-started-emulators "$PROJECT_PATH"/cordova/lib/list-started-emulators
cp "$BUILD_PATH"/bin/templates/cordova/lib/start-emulator "$PROJECT_PATH"/cordova/lib/start-emulator