[CB-2980] Added the install-emulator script

Reviewed by Jeffrey Heifetz <jheifetz@blackberry.com>
Tested by Tracy Li <tli@blackberry.com>
diff --git a/blackberry10/bin/templates/project/cordova/install-emulator b/blackberry10/bin/templates/project/cordova/install-emulator
new file mode 100644
index 0000000..b4aeb5c
--- /dev/null
+++ b/blackberry10/bin/templates/project/cordova/install-emulator
@@ -0,0 +1,23 @@
+#!/bin/sh
+<<COMMENT
+    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.
+COMMENT
+CORDOVA_DIR=$(dirname "$0")
+source "$CORDOVA_DIR/init"
+
+"$CORDOVA_NODE/node" "$CORDOVA_DIR/lib/install-emulator" "$@"
diff --git a/blackberry10/bin/templates/project/cordova/install-emulator.bat b/blackberry10/bin/templates/project/cordova/install-emulator.bat
new file mode 100644
index 0000000..9516315
--- /dev/null
+++ b/blackberry10/bin/templates/project/cordova/install-emulator.bat
@@ -0,0 +1,21 @@
+@ECHO OFF
+goto comment
+       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.
+:comment
+call "%~dps0init"
+"%CORDOVA_NODE%\node.exe" "%~dps0\lib\install-emulator" %*
diff --git a/blackberry10/bin/templates/project/cordova/lib/install-device b/blackberry10/bin/templates/project/cordova/lib/install-device
index c63cbee..5809a41 100644
--- a/blackberry10/bin/templates/project/cordova/lib/install-device
+++ b/blackberry10/bin/templates/project/cordova/lib/install-device
@@ -26,8 +26,11 @@
 options
     .usage('[--target=id]')
     .option('--target <id>', 'specifies the target to run the application')
+    .option('-k, --keystorepass <password>', 'the password of signing key; needed for creating debug token')
     .option('--query', 'query on the commandline when a password is needed')
+    .option('--devicepass <password>', 'device password')
     .option('--no-uninstall', 'does not uninstall application from device')
+    .option('--no-launch', 'do not launch the application on device')
     .on('--help', function() {
         console.log('  Examples:');
         console.log('');
@@ -43,6 +46,7 @@
 
 options.parse(process.argv);
 
+options.device = true;
 async.waterfall(
     [
         runUtils.getValidatedTarget.bind(this, options),
diff --git a/blackberry10/bin/templates/project/cordova/lib/install-emulator b/blackberry10/bin/templates/project/cordova/lib/install-emulator
new file mode 100644
index 0000000..972c475
--- /dev/null
+++ b/blackberry10/bin/templates/project/cordova/lib/install-emulator
@@ -0,0 +1,69 @@
+#!/usr/bin/env node
+
+/*
+ *  Copyright 2012 Research In Motion Limited.
+ *
+ * Licensed 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.
+ */
+
+var path = require("path"),
+    utils = require("./utils"),
+    options = require('commander'),
+    runUtils = require("./run-utils"),
+    logger = require("./logger"),
+    async = require("async");
+
+options
+    .usage('[--target=id]')
+    .option('--target <id>', 'specifies the target to run the application')
+    .option('--devicepass <password>', 'device password')
+    .option('--query', 'query on the commandline when a password is needed')
+    .option('-k, --keystorepass <password>', 'the password of signing key; needed for creating debug token')
+    .option('--no-uninstall', 'does not uninstall application from device')
+    .option('--no-launch', 'do not launch the application on device')
+    .on('--help', function() {
+        console.log('  Examples:');
+        console.log('');
+        console.log("  Deploying to a predefined target");
+        console.log('    $ run --target=Z10');
+        console.log('');
+    });
+process.argv.forEach(function (argument, index, args) {
+    if (argument.match(/^--target=/)) {
+        args.splice(index, 1, "--target", argument.substr("--target=".length));
+    }
+});
+
+options.parse(process.argv);
+
+options.emulator = true;
+async.waterfall(
+    [
+        runUtils.getValidatedTarget.bind(this, options),
+        runUtils.checkBuild,
+        runUtils.uninstall.bind(this, options),
+        runUtils.deployToTarget.bind(this, options)
+    ],
+    function (err) {
+        if (err) {
+            if (typeof err === "string") {
+                logger.error(err);
+                process.exit(1);
+            } else if (typeof err === "number") {
+                process.exit(err);
+            }
+        } else {
+            process.exit(0);
+        }
+    }
+);
diff --git a/blackberry10/bin/templates/project/cordova/lib/localize.js b/blackberry10/bin/templates/project/cordova/lib/localize.js
index 94d4673..38cf7a9 100755
--- a/blackberry10/bin/templates/project/cordova/lib/localize.js
+++ b/blackberry10/bin/templates/project/cordova/lib/localize.js
@@ -191,7 +191,7 @@
             "en": "No device PIN found, will omit debug token generation"
         },
         "WARN_NO_SIGNING_PASSWORD_PROVIDED": {
-            "en": "No signing password provided, debug token cannot be generated. Please enter a value for 'keystorepass' in %HOME%/.cordova/blackberry10.json or use --keystorepass via command-line directly from the project cordova scripts (WILL NOT WORK FROM CLI)."
+            "en": "No signing password provided, debug token cannot be generated. Please enter a value for 'keystorepass' in %HOME%/.cordova/blackberry10.json or use --keystorepass via command-line directly from the project cordova scripts."
         },
         "PROGRESS_GENERATING_DEBUG_TOKEN": {
             "en": "Generating debug token"
diff --git a/blackberry10/bin/templates/project/cordova/lib/run-utils.js b/blackberry10/bin/templates/project/cordova/lib/run-utils.js
index aff856e..18e8c58 100644
--- a/blackberry10/bin/templates/project/cordova/lib/run-utils.js
+++ b/blackberry10/bin/templates/project/cordova/lib/run-utils.js
@@ -27,6 +27,7 @@
     properties = utils.getProperties(),
     workingdir = path.normalize(__dirname + "/..");
 
+//Options looking for are: (Device | Emulator, query, devicepass). Calls back with:  (error || options object, target object)
 function getTargetName(options, done) {
     var ipFinder = options.device ? targetUtils.findConnectedDevice : targetUtils.findConnectedSimulator,
         targetType = options.device ? "device" : "emulator";
@@ -48,9 +49,12 @@
             devicePass: function (done) {
                 if (!options.devicepass && options.devicepass !== "") {
                     if (options.query) {
-                        utils.prompt({description: "Please enter your " + targetType +  " password: ", hidden: true}, done);
-                    } else {
+                        var description = options.device ? "Please enter your " + targetType +  " password: " : "Please enter your " + targetType +  " password (For no password press Enter): ";
+                        utils.prompt({description: description, hidden: true}, done);
+                    } else if (!options.emulator) {
                         done("Please provide device password using --devicepass");
+                    } else {
+                        done("");
                     }
                 } else {
                     done(null, options.devicepass);
@@ -62,7 +66,7 @@
                 done(err);
             } else {
                 options.devicepass = results.devicePass;
-                checkDeviceInfo(results.ip, targetType, results.devicePass, done);
+                _self.checkDeviceInfo(options, results.ip, targetType, results.devicePass, done);
             }
         });
     } else {
@@ -70,6 +74,7 @@
     }
 }
 
+//Options looking for are: (query, devicepass). Calls back with:  (error || target object)
 function validateTarget(options, targetName, allDone) {
     var deployTarget,
         err,
@@ -95,19 +100,19 @@
                 err = "IP is not defined in target \"" + target + "\"";
             }
         }
-
         if (!deployTarget.password && deployTarget.password !== "") {
             if (options.devicepass || options.devicepass === "") {
                 deployTarget.password = options.devicepass;
             } else {
                 if (options.query) {
                     runTasks.push(function (done) {
-                        utils.prompt({description: "Please enter your " + deployTarget.type +  " password: ", hidden: true}, function (e, devicePass) {
+                         var description = options.device ? "Please enter your " + deployTarget.type +  " password: " : "Please enter your " + deployTarget.type +  " password (For no password press Enter): ";
+                        utils.prompt({description: description, hidden: true}, function (e, devicePass) {
                             deployTarget.password = devicePass;
                             done(e);
                         });
                     });
-                } else {
+                } else if (!options.emulator) {
                     err = "Please provide device password using --devicepass or add one to the target " + deployTarget.name + " defined at " + utils.getPropertiesFilePath();
                 }
             }
@@ -119,15 +124,15 @@
         if (!finalErr && deployTarget) {
             logger.info("Target " + deployTarget.name + " selected");
         }
-        allDone(err || e, deployTarget);
+        allDone(err || e, options, deployTarget);
     });
 }
-//options are keystorepass, query
+//Options looking for are: (keystorepass, query). Calls back with:  (error || target object)
 function handleDebugToken(options, deployTarget, allDone) {
     options.keystorepass = options.keystorepass || properties.keystorepass;
 
     // if target has no pin, skip the debug token feature
-    if (deployTarget.pin) {
+    if (deployTarget.pin && !options.emulator) {
         async.waterfall(
             [
                 debugTokenHelper.checkDebugToken.bind(this, deployTarget.pin),
@@ -199,30 +204,32 @@
     }
 }
 
-function execNativeDeploy(options, callback) {
+function execNativeDeploy(deployOptions, callback) {
     var script = path.normalize(path.join(process.env.CORDOVA_BBTOOLS, "blackberry-deploy"));
 
-    utils.exec(script, options, {
+    utils.exec(script, deployOptions, {
         "cwd": workingdir,
         "env": process.env
     }, callback);
 }
 
 _self = {
-    //options looking for are: query, devicepass, password, target, (device || emulator)
+    //options looking for are: (query, devicepass, password, target, (device || emulator)) Function returns (error || deployTarget)
     getValidatedTarget : function (options, callback) {
         async.waterfall(
             [
                 getTargetName.bind(this, options),
                 validateTarget,
+                handleDebugToken,
             ], callback
         );
     },
-    //options looking for are: launch
+    //options looking for are: (launch) Function returns (error || null)
     deployToTarget : function (options, deployTarget, callback) {
         execNativeDeploy(generateDeployOptions(options, deployTarget, false));
     },
 
+    //options looking for are: (uninstall) Function returns (error || null)
     uninstall : function (options, deployTarget, allDone) {
         var script = path.join(process.env.CORDOVA_BBTOOLS, "blackberry-deploy"),
             args = [
@@ -250,8 +257,8 @@
             },
             function parsedConfigXMLOutput (result, done) {
                 if (installedAppsOutput.indexOf(result['@'].id) !== -1) {
-                    var options = generateDeployOptions(options, deployTarget, true);
-                    execNativeDeploy(options, done);
+                    var deployOptions = generateDeployOptions(options, deployTarget, true);
+                    execNativeDeploy(deployOptions, done);
                 } else {
                     done();
                 }
@@ -268,11 +275,11 @@
             );
     },
 
+    //Function returns (error || deployTarget)
     checkBuild : function (deployTarget, allDone) {
-        barPath = pkgrUtils.escapeStringForShell(
-            path.normalize(__dirname + "/../../build/" +
+        barPath = path.normalize(__dirname + "/../../build/" +
                 (deployTarget.type === "device" ? "device" : "simulator") +
-                "/" + utils.genBarName() + ".bar"));
+                "/" + utils.genBarName() + ".bar");
         if (fs.existsSync(barPath)) {
             allDone(null, deployTarget);
         } else {
@@ -281,7 +288,8 @@
 
     },
 
-    checkDeviceInfo : function (ip, deviceType, devicePass, done) {
+    //No options needed within function Function returns (error || options, targetName)
+    checkDeviceInfo : function (options, ip, deviceType, devicePass, done) {
         var props = utils.getProperties(),
         targetName;
 
@@ -295,7 +303,7 @@
                 };
                 utils.writeToPropertiesFile(props);
             }
-            done(err, targetName);
+            done(err, options, targetName);
         });
     }
 };