#!/bin/bash
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License along
#   with this program; if not, write to the Free Software Foundation, Inc.,
#   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

APPNAME="$1"
TYPE="$2"
DIR="/etc/zabbix/zabbix-discovery-generic"

# Checks
if [ -z "$APPNAME" ];then
   echo -n "NOT SUPPORTED"
   exit 1
fi

if ( ! (echo "$TYPE"|egrep -q "^(json|plain)$"));then
   echo -n "NOT SUPPORTED, USE 'json' or 'plain'"
   exit 1
fi

if (! echo "$APPNAME"|egrep -q "^[a-zA-Z0-9\.][a-zA-Z0-9\.]*$" );then
   echo -n "NOT SUPPORTED"
   exit 1
fi

# JSON ##################################################################
if [ "$TYPE" = "json" ];then

   cat <<'EOF'
   {
      "data":[
EOF

   # Example entry
   #      {
   #         "{#FSNAME}":"\/",
   #         "{#FSTYPE}":"rootfs"
   #      },

   FIRST=1
   shopt -s nullglob
   for FILE in $DIR/$APPNAME-*.json;
   do
      if [ "$FIRST" != "1" ];then
         echo -n ","
      fi
      FIRST=0
      cat $FILE
   done
   shopt -u nullglob
   cat <<'EOF'
             ]
   }
EOF

# PLAIN #################################################################
elif  [ "$TYPE" = "plain" ];then
   shopt -s nullglob
   for FILE in $DIR/$APPNAME-*.plain;
   do
      echo -n "'$(cat $FILE)',"
   done 
   shopt -u nullglob
fi
