#!/bin/sh -efu
#
# Copyright (C) 2020  Paul Wolneykien <manowar@altlinux.org>
#
# This file 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 St, Fifth Floor, Boston, MA 02110-1301, USA.
#

PROG="${0##*/}"
PROG_VERSION=0.1.0

SKIPLIST=ldap,ns
SKIP_SELF=1

if [ -e "$CONFDIR/$PROG.conf" ]; then
    . "$CONFDIR/$PROG.conf"
fi

if [ -z "$DOMAIN" ]; then
    DOMAIN="$(hostname -d)"
    if [ -z "$DOMAIN" ]; then
        echo "ERROR [$PROG]: Unable to detect the domain name" >&2
        exit 1
    fi
fi

selfaddr="$(host -t A $(hostname -f) | sed -e 's/^.*[[:space:]]\([^[:space:]]\+\)$/\1/')"

skip_host() {
    local name="$1"
    local addr="$2"
    local ret=

    if [ -n "$SKIP_SELF" ]; then
        ret=0
        echo "$selfaddr" | grep -qw "$addr" || ret=$?
        if [ $ret -eq 0 ]; then
            if [ -n "$DEBUG" ]; then
                echo "DEBUG [$PROG]: Skip $name as domain controller" &>2
            fi
            return 0
        fi
    fi

    if [ -n "$SKIPLIST" ]; then
        ret=0
        (
            IFS=,
            for sname in $SKIPLIST; do
                if [ "$name" = "$sname" ]; then
                    if [ -n "$DEBUG" ]; then
                        echo "DEBUG [$PROG]: $name is on the skiplist" &>2
                    fi
                    exit 0
                fi
            done
            exit 1
        ) || ret=$?

        if [ $ret -eq 0 ]; then
            return 0
        fi
    fi

    return 1
}

LANG=C host -l -t A "$DOMAIN" | \
    while read hostname _has_ _address_ address; do
        if [ "$hostname" = "$DOMAIN" ]; then
            continue
        fi
        hostname="${hostname%.$DOMAIN}"
        if skip_host "$hostname" "$address"; then
            continue
        fi
        printf '%s\t%s\t%s\n' "$hostname" "$address" "$HOSTGROUPS"
    done
