#!/usr/bin/env node
"use strict";
var gulp = require('gulp');
var path = require("path");
var replace = require('gulp-replace');

var rootdir = process.argv[2];

if (rootdir) {

  // go through each of the platform directories that have been prepared
  var platforms = (process.env.CORDOVA_PLATFORMS ? process.env.CORDOVA_PLATFORMS.split(',') : []);

  for(var x=0; x<platforms.length; x++) {

    var platform = platforms[x].trim().toLowerCase();

    if(platform == 'android') {
      var platformPath = path.join(rootdir, 'platforms', platform);
      var androidManifestFile = path.join(platformPath, 'AndroidManifest.xml');

      // Clean unused directories
      console.log('-----------------------------------------');
      console.log(' Updating file: ' + androidManifestFile);
      gulp.src(androidManifestFile)

        // Add 'tools' namespace to root tag
        .pipe(replace(/(xmlns:android="http:\/\/schemas.android.com\/apk\/res\/android")\s*>/g, '$1 xmlns:tools="http://schemas.android.com/tools">'))

        // <uses-sdk> : if many, keep only one
        .pipe(replace(/(<uses-sdk [^>]+>)(:?[\n\r\s\t ]*<uses-sdk [^>]+>)+/mg, '$1'))

        // <uses-sdk> : Replace 'targetSdkversion' and add tools:overrideLibrary
        .pipe(replace(/android:targetSdkVersion="[0-9]+"( tools:overrideLibrary="org.kaliumjni.lib")?\s*\/>/g, 'android:targetSdkVersion="25" tools:overrideLibrary="org.kaliumjni.lib" />'))

        .pipe(gulp.dest(platformPath));

      console.log('-----------------------------------------');
    }


  }
}


@@ -1031,43 +1031,29 @@
  // 
-%3Cuses-sdk%3E : if many, keep only one
+remove all %3Cuses-sdk%3E
 %0A   
@@ -1072,17 +1072,16 @@
 eplace(/
-(
 %3Cuses-sd
@@ -1091,51 +1091,16 @@
 %5E%3E%5D+
-%3E)(:?%5B%5Cn%5Cr%5Cs%5Ct %5D*%3Cuses-sdk %5B%5E%3E%5D+%3E)+/m
+%5C/%3E/
 g, '
-$1
 '))%0A
@@ -1110,16 +1110,20 @@
       //
+ add
  %3Cuses-s
@@ -1130,11 +1130,10 @@
 dk%3E 
-: R
+(r
 epla
@@ -1183,16 +1183,17 @@
 eLibrary
+)
 %0A       
@@ -1208,24 +1208,56 @@
 eplace(/
+(%3C%5C/manifest%3E)/, '    %3Cuses-sdk 
 android:
 targetSd
@@ -1240,38 +1240,35 @@
 ses-sdk android:
-target
+min
 SdkVersion=%22%5B0-9
@@ -1267,71 +1267,12 @@
 on=%22
-%5B0-9%5D+%22( tools:overrideLibrary=%22org.kaliumjni.lib%22)?%5Cs*%5C/%3E/g, '
+16%22 
 andr
@@ -1341,16 +1341,20 @@
 .lib%22 /%3E
+%5Cn$1
 '))%0A%0A   
@@ -1451,24 +1451,25 @@
 --------');%0A
+%0A
     %7D%0A%0A%0A  %7D%0A

fix android manifest