#!/bin/sh
source /usr/bin/flexa-install
source /usr/bin/flexa-config-lib

loga() 
{
    msg="$1 $2 $3"
    logger "flexa-agent: $msg"
    date=`date +'%T'`
    echo "$date flexa-agent: $msg"
}

FLEXABASEDIR=/mnt/data

device=$( qiba-spi-get-production-info.sh -c )
echo $device
if [ "${device}" == "Undefined" ] ; then
  echo "setting regid paths for Barionet"

  # device is a barionet  
  CONFDIR=/mnt/data/config
  REGIDJSON=/mnt/config/config.json
  device="barionet"
else
  echo "Setting regid paths for IPAM"
  # device is an ipam400 
  CONFDIR=${FLEXABASEDIR}/config
  REGIDPATH=${FLEXABASEDIR}/regId
  REGIDJSON=/mnt/shadow/config.json
  device="ipam400"
fi


TMPDIR=${FLEXABASEDIR}/tmp
NEWPACKAGE=${FLEXABASEDIR}/new_package
PACKAGENAME=package
PACKAGEZIP=${PACKAGENAME}.zip
PACKAGEPATH=${FLEXABASEDIR}/${PACKAGENAME}
ZIPPATH=${FLEXABASEDIR}/package.zip
SERVICEINFO=${CONFDIR}/service.json
APPINFO=${CONFDIR}/app.json
CONFIGFILE=${PACKAGEPATH}/config.json
STATE=${CONFDIR}/state.json
VERSIONPATH=${FLEXABASEDIR}/version
APPNAME_PY=${PACKAGEPATH}/run.py
APPNAME_LUA=${PACKAGEPATH}/default.lua

if [ "${device}" == "barionet" ] ; then 
  echo "setting paths for Barionet"
  tpl_path=/etc/config/flexa_app_tpl
  uci_config_path=/etc/config/flexa_app
else 
  echo "Setting paths for IPAM"
  tpl_path=/barix/local/config/flexa_app_tpl
  uci_config_path=/barix/local/config/flexa_app
fi

mkdir -p ${FLEXABASEDIR}
mkdir -p ${NEWPACKAGE}
mkdir -p ${CONFDIR}

do_reboot=false
do_reset_uci=true
max_timeout=5  # timeout for flexa-calls
n_reconnects=0
update_rate=0
max_reconnects=3
version=$( uci get flexa_agent.service.package_version )   
registry_url=$( uci get flexa_agent.registry.registry_url )
#regid=$(cat ${REGIDPATH})
#regid=$( jq -r '.registrationId' ${REGIDPATH} )
#uci set flexa_agent.registry.regid=${regid}
#uci commit




usage() {
  echo " "
  echo "-------------------------------------------------------------------------------------"
  echo "no argument:    flexa-agent checks status and takes required actions"
  echo "usb [mountdir]  flexa-agent checks [mountdir] for new package"
  echo "reset           flexa-agent resets uci configuration"
  echo "clean           flexa-agent resets uci configuration and removes installed packages"
  echo "install         flexa-agent installs the package.zip located in /mnt/data"
  echo "-------------------------------------------------------------------------------------"
}


clean() {
  echo "removing old package and config..."
  if [ -d ${PACKAGEPATH} ]; then 
    rm -rf ${PACKAGEPATH}
  fi
  if [ -d ${NEWPACKAGE} ]; then
    rm -rf ${NEWPACKAGE}
  fi
  if [ -f ${ZIPPATH} ]; then 
    rm -rf ${ZIPPATH}
  fi
  if [ -d ${CONFDIR} ]; then 
    rm ${CONFDIR}/*
  fi
  echo "removing old package and config... Done!"
}


get_registration_id() {
  # flexa prototypes have the regid written to /mnt/data/regid
  # produced devices have the regid inside the config.json in 
  # /mnt/shadow/config.json
  # if the device has no regid at all, flexa will not work! 
  if [ -f "${REGIDJSON}" ]; then
    regid=$( jq -r '.registrationId' ${REGIDJSON} )
    uci set flexa_agent.registry.regid=${regid}
    uci commit
  elif [ -f "${REGIDPATH}" ]; then
    regid=$(cat ${REGIDPATH} )
    uci set flexa_agent.registry.regid=${regid}
    uci commit
  else
    logger "ERROR: Device has no registration ID assigned!"
    echo "ERROR: Device has no registration ID assigned!"
  fi 
}

contact_registry() {
  loga "Contacting registry..."
  registry_response=$( request_registry_info ${SERVICEINFO} ${regid} ${registry_url} )
  echo "Registry response: "${registry_response}
  if [ "${registry_response}" = "200" ]; then
    contact_service
  else 
    loga "Contacting registry failed, exit agent!"
    exit 100
  fi
  loga "Contactng registry... Done!"
}


check_appl_status() {
  loga "Check state..."

  service_url=$( uci get flexa_agent.service.service_url )
  if [ "${service_url}" != "changeme" ] ; then
    echo "request status: "${STATE} ${regid} ${service_url} 
    status_response=$( request_status_info ${STATE} ${regid} ${service_url} )
    echo "request status: "${STATE} ${regid} ${service_url}" receiving response "${status_response}
    if [ "${status_response}" = "200" ]; then

      state=$( jq -r '.config' ${STATE} ) 
      if [ ${state} = "sync" ]; then
        logger "application in sync with service configuration. Stopping flexa-client."
        echo "application in sync... exit agent!"
        exit 400
      fi

      else 
      echo "application not in sync... contact service!"
      contact_service    
    fi
  else 
    echo "status url not known -> contact service "
    contact_service
  fi

}


contact_service() {
  loga "Contacting service..."
  service_url=$( uci get flexa_agent.service.service_url )
  if [ "${service_url}" = "changeme" ]; then
    loga "Service URL not kown -> contact registry"
    contact_registry
  
  else

    service_response=$( request_service_info ${APPINFO} ${regid} ${service_url} )
    echo "Service response: "${service_response}

    getConfigUrl=$( jq -r '.getConfigUrl' /mnt/data/config/app.json | awk '{ print $2 }' )
    config_url=$( uci get flexa_agent.service.config_url )
    package_url=$( uci get flexa_agent.service.package_url )
    old_version=$( get_app_version ${APPINFO} )
    echo ${APPINFO}
    loga "Downloading package..."
    echo "Contacting service: downloading package from  ${package_url} to ${ZIPPATH}..."
    package_response=$( get_package ${old_version} "${package_url}" ${ZIPPATH} )
    echo "Contacting service: downloading package, received response "${package_response}
    loga "Contacting service: downloading package... Done!"
    
    if [ "${package_response}" = "200" ]; then
      echo "contacting service: installing package..." 	
      # dealing with change in extension.	    
      unzip "${ZIPPATH}" -d ${NEWPACKAGE} || tar -xvf "${ZIPPATH}" -C ${NEWPACKAGE} || tar -xvf "${ZIPPATH}" -C ${NEWPACKAGE}
      rm -rf ${PACKAGEPATH}
      mkdir -p ${PACKAGEPATH}
      do_install ${NEWPACKAGE} ${PACKAGEPATH} "${device}"
      do_reboot=true
      loga "Contacting service: installing package... Done!"
    fi

    loga "Contacting service: getting configuration..."
    get_config ${CONFIGFILE} ${regid} ${config_url}
    loga "Contacting service: getting configuration... Done!"

  fi
  loga "Contacting service... Done!"
}


# checks if the inserted usb-drive has a different application
# package than the one installed at /mnt/data
# 
# parameters:
#   $1: mount-dir

get_app_usb() {
  usb_update=$(uci get flexa_agent.service.enable_usb_update)
  if [ "${usb_update}" = "false" ]; then
     logger "USB Application Package update is disabled"
     echo "USB Application Package update is disabled"
     exit 200
  fi
  
  logger "Check usb drive ${1} for application package..."
  echo "check usb drive ${1} for application package..."
  if [ -f ${ZIPPATH} ];then
    MD5SUMOLD=$( md5sum ${ZIPPATH} | awk '{ print $1 }' ) 
  else
    MD5SUMOLD=0
  fi  
  # get md5 sum of new package  
  if [ -e ${1}/${PACKAGEZIP} ]; then
    MD5SUMNEW=$( md5sum ${1}/${PACKAGEZIP} | awk '{ print $1 }' )
    
  else 
    logger ${1}/${PACKAGEZIP}
    echo "check usb drive ${1} for application package... no package found"
    logger "Check usb drive ${1} for application package... No package found!"
    exit 200
  fi
  logger ${MD5SUMNEW} " " ${MD5SUMOLD}
  if [ ${MD5SUMNEW} != ${MD5SUMOLD} ];then
    reset_flexa_agent_config
    reset_flexa_app_config ${tpl_path} ${uci_config_path}
    echo "check usb drive ${1} for application package... new package found, installing..."
    logger "new application package found on usb drive, installing..." 
    cp $1/${PACKAGEZIP} ${ZIPPATH}  
    tar -xvf ${ZIPPATH} -C ${NEWPACKAGE} || unzip ${ZIPPATH} -d ${NEWPACKAGE} || tar -xvf ${ZIPPATH} -C ${NEWPACKAGE}
    rm -rf ${PACKAGEPATH}
    mkdir -p ${PACKAGEPATH}
    do_install ${NEWPACKAGE} ${PACKAGEPATH} "${device}"
    echo "check usb drive ${1} for application package... new package found, installing...done!"
    logger "new application package found on usb drive, installing..."
    if [ -f ${CONFIGFILE} ]; then
      app_param_to_uci ${CONFIGFILE}
    fi

    do_reboot=true
  else 
    echo "no new application package found on usb drive"
    logger "no new application package found on usb drive"
    exit 200
  fi

  
}


if [ $# -eq 0 ]; then
  get_registration_id

  dir_ok=$( check_flexa_directories )
  if [ ${dir_ok} = "200" ]; then
    check_appl_status 
  else
    contact_registry
  fi

elif [ $1 = "clean" ]; then
  clean
  reset_flexa_agent_config
  reset_flexa_app_config ${tpl_path} ${uci_config_path}

elif [ $1 = "reset" ]; then
  
  reset_flexa_agent_config
  reset_flexa_app_config ${tpl_path} ${uci_config_path}

elif [ $1 = "install" ]; then

  unzip ${ZIPPATH} -d ${NEWPACKAGE} || tar -xvf ${ZIPPATH} -C ${NEWPACKAGE} || tar -xvf ${ZIPPATH} -C ${NEWPACKAGE}
  rm -rf ${PACKAGEPATH}
  mkdir -p ${PACKAGEPATH}
  do_install ${NEWPACKAGE} ${PACKAGEPATH} "${device}"

elif [ $1 = "install_webui" ]; then
  install_webui ${PACKAGEPATH} "${device}"

elif [ $1 = "usb" ]; then
  if [ -d "$2" ]; then
   get_app_usb $2
  
  else 
    usage
  fi
elif [ $1 = "help" ]; then

  usage
fi



if ${do_reboot}; then
  reboot
fi
