#!/bin/bash

set -e

# Copyright (C) 2017 Mike Gabriel <mike.gabriel@das-netzwerkteam.de>
#
# 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.

# FIXME: MAKE THIS MORE GENERIC BEFORE PUSHING!!!!

ldapsearch -xLLL "(&(cn=*)(|(objectClass=ipHost)(objectClass=GOHard)))" \
    cn ipHostNumber macAddress description 2>/dev/null | perl -p0e 's/\n //g' | \
while read KEY VALUE ; do
	case "$KEY" in
		dn:)
			HOSTNAME= ; IP= ; MAC= ; DESC= ; DN=${VALUE}
			OU=$(echo $DN | sed -r -e 's/cn=[^,]+,ou=[^,]+,ou=[^,]+,ou=([^,]+),.*/\1/' | sed -r -e 's/cn=[^,]+,ou=[^,]+,ou=[^,]+,dc=.*/Servers/g')
		;;
		cn:) HOSTNAME="${VALUE}";;
		ipHostNumber:) IP="${VALUE}";;
		macAddress:) MAC="${VALUE}";;
		description:) DESC="${VALUE}";;
		"")
			if [ -n "$DESC" ]; then DESC="\"${DESC}\""; fi
			echo "${OU},${HOSTNAME},${IP},${MAC},${DESC}"
		;;
	esac
done

exit 0
