#!/bin/bash
LOG=/tmp/sdk.log

APP_NAME=$(basename $(dirname $(dirname $0)))
HTTP_STATUS=200
ERROR_MESSAGE="Unknown error"

check_webauth() {
  # check if auth is enabled/disabled
  if [ -f $WEB_XML_LOCK ]; then
    # disabled
    WEB_AUTHMGMNT_STATE="{\"enableWebAuth\": false}"
  else
    # enabled
    WEB_AUTHMGMNT_STATE="{\"enableWebAuth\": true}"
  fi
  return 0
}

switch_webauthmgmnt() {
  if [ "$CONTENT_LENGTH" -gt 0 ]; then
    POST_DATA=$(cat -)
  fi
  ENABLE=$(echo $POST_DATA | jq -r '.enableWebAuth')
  [[ -z "$ENABLE" ]] && {
    HTTP_STATUS=400
    ERROR_MESSAGE="Inavalid request"
    return 2
  }
  [[ $ENABLE == "null" ]] && {
    HTTP_STATUS=400
    ERROR_MESSAGE="Parameter 'enableWebAuth' is required."
    return 3
  }
  if [[ $ENABLE == "true" ]]; then
    rm -f $WEB_XML_LOCK || {
      HTTP_STATUS=500
      ERROR_MESSAGE="Unable to delete '$WEB_XML_LOCK' file"
      return 51
    }
  elif [ $ENABLE == "false" ]; then
    echo -n "" >$WEB_XML_LOCK || {
      HTTP_STATUS=500
      ERROR_MESSAGE="Unable to create '$WEB_XML_LOCK' file."
      return 52
    }
    chmod 664 $WEB_XML_LOCK || {
      HTTP_STATUS=500
      ERROR_MESSAGE="Unable to set '$WEB_XML_LOCK' file permissions."
      return 53
    }
  else
    HTTP_STATUS=400
    ERROR_MESSAGE="Inavalid request"
    return 4
  fi
}

main() {
  WEB_RESOURCES=$(xmlstarlet sel -t -m "application/web_resources" -v . -n /home/$APP_NAME/app.conf)
  if [ ! -z $WEB_RESOURCES ]; then # if <web_resources>...<web_resources> is present in app.conf
    WEB_XML_LOCK="/home/$APP_NAME/$WEB_RESOURCES.lck"
    if [ "$REQUEST_METHOD" = "GET" ]; then
      check_webauth
    elif [ "$REQUEST_METHOD" = "POST" ]; then
      switch_webauthmgmnt
    else
      {
        HTTP_STATUS=400
        ERROR_MESSAGE="Invalid request"
        STATUS_CODE=1
      }
    fi
    STATUS_CODE=$?
  else
    {
      HTTP_STATUS=500
      ERROR_MESSAGE="No 'web_resources' is present in app.conf file."
      STATUS_CODE=50
    }
  fi

  echo "Status: $HTTP_STATUS"
  echo "Content-type: application/json"
  echo ""
  if [ "$STATUS_CODE" -ne 0 ]; then
    echo "{\"errorCode\": \"$STATUS_CODE\", \"errorMessage\": \"$ERROR_MESSAGE\"}"
  else
    if [ "$REQUEST_METHOD" = "GET" ]; then
      echo "$WEB_AUTHMGMNT_STATE"
    else
      echo "{}"
    fi
  fi

}
main
