#!/bin/bash
#Attempt to gain a WAN connection for MDM Registration to query for this device's MDM account ID
#PREREQ: Firewall allows outgoing DHCP requests and MDM Client connection

CONFIG_FILE="/var/config/devicehq/config.json"
STATUS_FILE="/var/config/devicehq/status.json"

if [ ! -f $CONFIG_FILE ]; then
    logger -t callhome "Config file missing!"
    logger -t callhome "Do: mkdir /var/config/devicehq"
    logger -t callhome "Then: cp /opt/devicehq/config.json.sample /var/config/devicehq/config.json"
    exit 1
fi

JSON=$(cat $CONFIG_FILE)
ENABLED=$( echo $JSON | jsparser -p /enabled )
KEY=$( echo $JSON | jsparser -p /accountKey )
MDM_URL=$( echo $JSON | jsparser -p /deviceHqUrl )

if [ "$ENABLED" != "true" ]; then
    logger -t callhome "Not calling home because DeviceHQ is disabled in /var/config/devicehq/config..json."
    exit 1
fi

UUID=$(mts-io-sysfs show uuid)
DEVID=$(mts-io-sysfs show device-id)


MDM_REG_URL="$MDM_URL/api/v1/register-device"
TMPFILE="/var/run/callhome"
DONE=false
FORCE=false
WAN_AVAILABLE=true
MAX_ATTEMPTS=0 #Infinite
INTERVAL_SECONDS=30

#Gather options from command line
# Reset in case getopts has been used previously in the shell.
OPTIND=1

function show_help() {
  echo "Usage: $0 -k <ACCOUNT KEY> -a <MAX ATTEMPTS> -i <INTERVAL SECONDS>"
}

while getopts "h?k:a:i:d:u:m:f" opt; do
    case "$opt" in
    h|\?)
        show_help
        exit 0
        ;;
    k)  KEY=$OPTARG
        ;;
    a)  MAX_ATTEMPTS=$OPTARG
        ;;
    a)  INTERVAL_SECONDS=$OPTARG
        ;;
    f)  FORCE=true
        ;;
    d)  DEVID=$OPTARG
        ;;
    u)  UUID=$OPTARG
        ;;
    m)  MDM_URL=$OPTARG
        ;;
    esac
done

shift $((OPTIND-1))

[ "$1" = "--" ] && shift

if [ "$FORCE" == "true" ]; then
  DONE=false
fi


function checkCallHomeNeeded() {
  if [ "$FORCE" != "true" ]; then
    JSON=$(cat $CONFIG_FILE)
    KEY=$( echo $JSON | jsparser -p /accountKey )

    LAST_CONNECTED="unknown"
    STATUS=""
    if [ -f $STATUS_FILE ]; then
      JSON=$(cat $STATUS_FILE)
      LAST_CONNECTED=$( echo $JSON | jsparser -p /lastConnected )
      STATUS=$( echo $JSON | jsparser -p /status )
    fi

    if [ "$KEY" != "" ] && [ $LAST_CONNECTED != "unknown" ] && [ $STATUS == "idle" ]; then
      echo "Found that Call-Home Not Needed"
      exit 0
    fi
  fi
}

function saveConfigs() {
  logger -t callhome "Saving accountKey"

  sed -i "s/\"accountKey\"\s*:\s*\".*\"/\"accountKey\": \"$KEY\"/" $CONFIG_FILE

  if [ $? != 0 ]; then
    logger -t callhome "Failed to add account key [$KEY] to $CONFIG_FILE"
  fi
}

function checkForCheckIn() {

  i=0
  while [  $i -lt 10 ]; do
    if [ -f $STATUS_FILE ]; then
      JSON=$(cat $STATUS_FILE)
      LAST_CONNECTED=$( echo $JSON | jsparser -p /lastConnected )
      STATUS=$( echo $JSON | jsparser -p /status )
      if [ "$LAST_CONNECTED" == "unknown" ] || [ $STATUS != "idle" ]; then
        logger -t callhome "MDM client has not checked-in yet"
      else
        logger -t callhome "SUCCESS! MDM Client has checked-in."
        DONE=true
        return
      fi
    else
      logger -t callhome "MDM client has not checked-in yet"
    fi

    let i=i+1
    logger -t callhome "Sleeping for 30 seconds."
    sleep 30
  done

}

function attemptMdmRegistration() {

  logger -t callhome "Attempting to register with MDM"
  CODE=$( curl -m 20 -ks -o $TMPFILE -w "%{http_code}" -X POST -H "Content-Type: application/json" \
            -d '{ "device_id" : "'$DEVID'", "uuid" : "'$UUID'"  }' \
            $MDM_REG_URL )

  if [ $? == 0 ]; then
    if [ "$CODE" == "200" ]; then
      logger -t callhome "Registered with MDM.  Checking for Account Key"

      #Request returned 200
      KEY=$( cat $TMPFILE | jsparser -p /account_key )
      if [ $? == 0 ]; then
        if [ "$KEY" != "" ]; then
          logger -t callhome "Received Account Key! [$KEY]"
          saveConfigs
          /etc/init.d/annex-client start
          checkForCheckIn
        else
          logger -t callhome "Account Key not returned.  This device may not be registered with a user account"
        fi
      else
        RESULT=$(cat $TMPFILE)
        logger -t callhome "Error: Unexpected MDM Registration Server response: $RESULT"
      fi
    else
      RESULT=$(cat $TMPFILE)
      logger -t callhome "Error: MDM Registration Failed with Device ID [$DEVID] and UUID [$UUID]"
      logger -t callhome "Error: MDM Registration Server Response Header Code: $CODE"
      logger -t callhome "Error: MDM Registration Server Response Body Content: $RESULT"
    fi
  else
    logger -t callhome "Warning: Could not connect to MDM server: $MDM_REG_URL"
  fi
}

logger -t callhome "Setting Up Call-Home "
COUNT=0

while [ $DONE == false ]; do
  logger -t callhome "Attempts: $COUNT"

  checkCallHomeNeeded

  attemptMdmRegistration

  COUNT=$(($COUNT+1))
  if [ $MAX_ATTEMPTS != 0 ] && [ $COUNT -gt $MAX_ATTEMPTS ]; then
    DONE=true
    logger -t callhome "Reached Maximum Attempts [$MAX_ATTEMPTS]"
  fi

  if [ $DONE == false ]; then
    logger -t callhome "Sleeping for $INTERVAL_SECONDS seconds before next attempt"
    sleep $INTERVAL_SECONDS
  fi

done

