#!/bin/bash

if [ -z "${ONE_LOCATION}" ]; then
    LIB_LOCATION=/usr/lib/one
else
    LIB_LOCATION=$ONE_LOCATION/lib
fi

. $LIB_LOCATION/sh/scripts_common.sh

DRIVER_PATH=$(dirname $0)
source ${DRIVER_PATH}/../../datastore/libfs.sh

UTILS_PATH="${DRIVER_PATH}/../../datastore"


# # # get arguments

DRV_ACTION=$1
ID=$2

XPATH="$UTILS_PATH/xpath.rb -b $DRV_ACTION"

unset i XPATH_ELEMENTS

while IFS= read -r -d '' element; do
    XPATH_ELEMENTS[i++]="$element"
done < <($XPATH     /MARKET_DRIVER_ACTION_DATA/MARKETPLACE/ID \
                    /MARKET_DRIVER_ACTION_DATA/MARKETPLACE/TEMPLATE/BRIDGE_LIST \
                    /MARKET_DRIVER_ACTION_DATA/MARKETPLACE/TEMPLATE/ENDPOINT)
unset i

MARKETPLACE_ID="${XPATH_ELEMENTS[i++]}"
BRIDGE_LIST="${XPATH_ELEMENTS[i++]}"
ENDPOINT="${XPATH_ELEMENTS[i++]}"


if [ -z "$ENDPOINT" ]; then
    echo "Variable ENDPOINT is not set" 2>&1
    exit 1
fi

MONITOR_SCRIPT="curl -sSL \"$ENDPOINT\""

if [ -n "$BRIDGE_LIST" ]; then
    HOST=`get_destination_host`
    MONITOR_DATA=$(ssh_monitor_and_log "$HOST" "$MONITOR_SCRIPT" "Remote monitor script" 2>&1)
else
    MONITOR_DATA=$(monitor_and_log "$MONITOR_SCRIPT" "Monitor script" 2>&1)
fi

MONITOR_STATUS=$?


# # # delete local error app

AppList="$(eval $MONITOR_SCRIPT)"
ArrayApp=($(echo "$AppList" | awk '{gsub(/(APP=)|(")/,"");print}'))
selSorce=()
for App in ${ArrayApp[@]}; do
  decApp="$(echo "$App" | base64 -d)"
  source_img="$(echo "$decApp" | awk -F'/' '/^SOURCE/ {gsub(/(SOURCE=)|(")/,"");print}')"
  selSorce+=( "$source_img" )
done
if [ -n "${selSorce[@]}" ]; then
    localMarketApp="$(/usr/bin/onemarketapp list -x)"
    slocArray=($(echo "$localMarketApp" | xmlstarlet sel -t -v "/MARKETPLACEAPP_POOL/MARKETPLACEAPP[MARKETPLACE_ID=$MARKETPLACE_ID]/SOURCE" -n))
    for sloc in ${slocArray[@]}; do
      if ! echo "${selSorce[@]}" | grep -qw "$sloc"; then
        IDerrApp=$(echo "$localMarketApp" | xmlstarlet sel -t -v '/MARKETPLACEAPP_POOL/MARKETPLACEAPP[SOURCE="'$sloc'"]/ID')
        [ -n "$IDerrApp" ] && /usr/bin/onemarketapp delete $IDerrApp
      fi
    done
fi

# # # 

if [ "$MONITOR_STATUS" = "0" ]; then
    echo "$MONITOR_DATA" | tr ' ' '\n'
    exit 0
else
    echo "$MONITOR_DATA"
    exit $MONITOR_STATUS
fi
