#!/bin/sh
source "/opt/gira/bin/environment"

echo "called with "

if [[ $# -eq 0 ]] ; then
  LOGFILENAME="${GENLOGFILETMP}"/logfile.zip
else 
  LOGFILENAME="$1"
fi

mkdir -p ${GENLOGFILETMP}

OVERWRITEZIP='minizip -o -1'
ADDTOZIP='minizip -a'
if [ -f /usr/bin/zip ]; then 
  OVERWRITEZIP='zip -g'
  ADDTOZIP='zip -g'
fi

if [[ $# -eq 0 ]] ; then
# minizip cannot store folders and it seems to store only one folder level per command...
${OVERWRITEZIP} ${LOGFILENAME} ${DEFAULT_LOG_DIR}/*.* ${DEFAULT_LOG_DIR}/messages
fi
${ADDTOZIP} ${LOGFILENAME} ${DEFAULT_LOG_DIR}/samba/*
${ADDTOZIP} ${LOGFILENAME} ${PERSISTENT_LOG_DIR}/*

ps w > /tmp/ps_w.txt
cd /tmp
${ADDTOZIP} ${LOGFILENAME} ps_w.txt
rm -f /tmp/ps_w.txt

ps l > /tmp/ps_l.txt
cd /tmp
${ADDTOZIP} ${LOGFILENAME} ps_l.txt
rm -f /tmp/ps_l.txt

dmesg > /tmp/dmesg.txt
cd /tmp
${ADDTOZIP} ${LOGFILENAME} dmesg.txt
rm -f /tmp/dmesg.txt

uptime > /tmp/uptime.txt
cd /tmp
${ADDTOZIP} ${LOGFILENAME} uptime.txt
rm -f /tmp/uptime.txt

df -h > /tmp/df.txt
cd /tmp
${ADDTOZIP} ${LOGFILENAME} df.txt
rm -f /tmp/df.txt

/opt/gira/bin/devcfg > /tmp/devcfg.txt
cd /tmp
${ADDTOZIP} ${LOGFILENAME} devcfg.txt
rm -f /tmp/devcfg.txt

wget http://127.0.0.1:65155/status.html -O /tmp/DeviceStatus.html 2>/dev/null
if [ ! -s /tmp/DeviceStatus.html ]; then
  echo "get index.html instead"
  wget http://127.0.0.1:65155/index.html -O /tmp/DeviceStatus.html 2>/dev/null
fi
cd /tmp
${ADDTOZIP} ${LOGFILENAME} DeviceStatus.html
rm -f /tmp/DeviceStatus.html

# The IscWebservice will generate COStates and DeviceInfo files
if [ -f /tmp/deviceinfo.json ]; then 
cd /tmp
${ADDTOZIP} ${LOGFILENAME} deviceinfo.json
rm -f /tmp/deviceinfo.json
fi

if [ -f /tmp/coStates.json ]; then 
cd /tmp
${ADDTOZIP} ${LOGFILENAME} coStates.json
rm -f /tmp/coStates.json
fi

if [ -f /opt/userdata/isc/sdk.crt ]; then 
  ${ADDTOZIP} ${LOGFILENAME} /opt/userdata/isc/sdk.crt 
fi

if [ -f /opt/userdata/isc/appfiles.xml ]; then 
  ${ADDTOZIP} ${LOGFILENAME} /opt/userdata/isc/appfiles.xml /opt/userdata/isc/appfiles.xml.SHA256.sig
fi

if [ -f /opt/userdata/devicestack/iscOM/config.json ]; then 
  ${ADDTOZIP} ${LOGFILENAME} /opt/userdata/devicestack/iscOM/config.json
fi

if [[ $# -eq 0 ]] ; then
# add product specific files, default is /opt/userdata/iscAppConfigRoot
source "/opt/gira/bin/product_logfiles.sh"

product_logfiles
fi
