#!/bin/sh
#Changing to the cloned repo and setting the correct envs to make sure node and ionic are available
cd $XCS_PRIMARY_REPO_DIR
PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/Library/Frameworks/Mono.framework/Versions/Current/Commands"
. ~/.bash_profile
bundle install

if [ -f 'ionic/ionic.config.json' ]; then

  #Adding the iOS Platform
  cd ionic
  npm install
  ionic cordova platform add ios

  #Reading the server_config.json for the server details
  host=$(node -pe 'JSON.parse(process.argv[1]).mfp.host' "$(cat ../mfpconfig/server_config.json)")
  port=$(node -pe 'JSON.parse(process.argv[1]).mfp.port' "$(cat ../mfpconfig/server_config.json)")
  protocol=$(node -pe 'JSON.parse(process.argv[1]).mfp.protocol' "$(cat ../mfpconfig/server_config.json)")
  mfpURL="${protocol}://${host}:${port}"
  echo "MFP -----> ${mfpURL}"

  #Creating a node script to update the config.xml with the mfp server URL
  mkdir node
  cd node
  touch server.js
  npm init -y
  npm install xml2json;

  echo "var fs = require('fs');
  var parser = require('xml2json');

  fs.readFile( '../config.xml', function(err, data) {
    var json = JSON.parse(parser.toJson(data, {reversible: true}));
    var required = json['widget']['mfp:server']['url'];
    console.log(required);
    json['widget']['mfp:server']['url']  = '$mfpURL';
    console.log(json['widget']['mfp:server']['url']);
    var stringified = JSON.stringify(json);
    var xml = parser.toXml(stringified);
    fs.writeFile('../config.xml', xml, function(err, data) {
      if (err) {
        console.log(err);
      }
      else {
        console.log('Updated the config file');
      }
    });

  });" >> server.js

  node server.js

  echo "\n\n Checking the config.xml file\n\n";

  cat ../config.xml

  cd ..
  #Doing cordova prepare to update the plist file and js sources
  ionic cordova prepare ios
  
  cat platforms/ios/Storefront/Resources/mfpclient.plist
  
  cat config.xml

else

  echo "Not an ionic Project"

  pod update

  if [ -f 'mfpclient.plist' ]; then

    host=$(node -pe 'JSON.parse(process.argv[1]).mfp.host' "$(cat mfpconfig/server_config.json)")
    port=$(node -pe 'JSON.parse(process.argv[1]).mfp.port' "$(cat mfpconfig/server_config.json)")
    protocol=$(node -pe 'JSON.parse(process.argv[1]).mfp.protocol' "$(cat mfpconfig/server_config.json)")
    
    echo "BEFORE --------";
    cat mfpclient.plist

    plutil -replace protocol -string "${protocol}" mfpclient.plist
    
    plutil -replace host -string "${host}" mfpclient.plist
    
    plutil -replace port -string "${port}" mfpclient.plist
    
    echo "AFTER --------";
    cat mfpclient.plist

  fi

fi