#!/usr/bin/perl
#
# Copyright (c) 2023 Mathieu Roy <yeupou--gnu.org>
#        http://yeupou.wordpress.com/
#
#   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., 59 Temple Place, Suite 330, Boston, MA  02111-1307
#   USA

use strict;
use Sys::Syslog qw(:standard);
use File::Basename;
use Net::IP qw(ip_is_ipv4 ip_is_ipv6);

my $confdir = "/etc/exim4";
my $domainsconf = "$confdir/final_from_domains";
my $hostsconf = "$confdir/final_from_hosts";
my $digbin = "/usr/bin/dig";

# exit if no DOMAINS are set (meanin the feature is probably not active)
exit unless -e $domainsconf;

openlog(basename($0), 'nofatal', 'mail');

# otherwise, fill HOST with IP of domains listed in DOMAINS
open(DOMAINS, "< $domainsconf");
my (%hosts, %isnew, %isobsolete);
while (<DOMAINS>){
    chomp();
    next if /^$/;
    next if /^#/;
    next if /^;;/;
    open(DIG, "$digbin +short $_|");
    while(<DIG>) {
	chomp();
	next unless ip_is_ipv4($_) or ip_is_ipv6($_);
	$hosts{$_} = 1;
	$isnew{$_} = 1;
    }
}
close(DOMAINS);

# slurp data from current file
open(HOSTS, "< $hostsconf");
while (<HOSTS>){
    chomp();
    next unless ip_is_ipv4($_) or ip_is_ipv6($_);
    if (exists($hosts{$_})) {
	# IP wanted are already found, remove the new marker
	delete($isnew{$_});
    } else {
	# no longer wanted, mark as obsolete
	$isobsolete{$_} = 1;
    }
}
close(HOSTS);

# update host if there are new or obsolete IP
if (keys(%isnew) or keys(%isobsolete)) {
    syslog('info', "update $hostsconf (".keys(%isnew)." new, ".keys(%isobsolete)." obsolete)"); 
    open(HOSTS, "> $hostsconf");
    foreach my $host (sort(keys %hosts)) {
	print HOSTS "$host\n";
    }
    close(HOSTS);
}



# EOF
