#!/usr/bin/bash
BASEDIR=/var/lib/zabbix-agent/mysql-db-discovery/
DURATION=86400
NOW="$(date +%s)"

# Create state files for each database entry
OLDIFS=$IFS
IFS=$'\n' # Seperate on newlines with only

# Build array of databases
LIVEDBS=( $(env HOME=/var/lib/zabbix mysql -NB -e "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME NOT LIKE '%\_schema' AND SCHEMA_NAME <> 'lost+found'") )

# Dump all array elements (database names)
IFS=$OLDIFS
ARGS=()
# Build our find command arguments
for f in "${LIVEDBS[@]}"; do
	# Append -or after each element but not before the first element
	[[ "${#ARGS[@]}" -gt 0 ]] && ARGS+=( -or )
	# Create an iname match for each element
	ARGS+=( -iname "$f".state )
done

# Are there database state files which do not match any of the database names in our array?
# This means the database has been removed and we should delete the state file so zabbix will stop discovering it
find $BASEDIR -maxdepth 1 -type f -iname "*.state" -not \( "${ARGS[@]}" \) -delete

IFS=$'\n' # seperate on newlines with only
OUTPUT="$( 
for f in "${LIVEDBS[@]}"; do
	# State Files
	STFILES="$BASEDIR""$f".state

	# If the state file doesn't already exist create it (e.g. first run or new database)
	if [[ ! -f "$STFILES" ]]; then
		cat <<-EOD > "$STFILES"
			###############################################################################################
			# Issue #51425 - This STATE file was automatically generated
			# by $(readlink -f "$0") on $(date)
			# This file must exist for zabbix to discover the "$f" database
			###############################################################################################
		EOD

	# For existing state files
	else
		# If they were last modified more than 1day ago
		CREATED="$(date +%s -r "$STFILES")"
		AGE="$(($NOW - $CREATED))"
		if [[ "$AGE" -gt "$DURATION" ]]; then
			# Print the database name
			echo $f | sed -re 's/^(.*)/  {"{#DBNAME}":"\1"},/g'
		fi
	fi
# JSONify it for zabbix
done | sed -re '1s/^/{"data":[\n/; $s/,//; $ s/$/\n]}/; /^$/d'
)"

# Print the output if it exists
if [[ ! -z "$OUTPUT" ]]; then
	printf '%s\n' "${OUTPUT}"
else
	# Print empty JSON if we have nothing to output
	printf "{\"data\":[\n]}\n"
fi
