#!/usr/bin/perl

use strict;
use warnings;

use Getopt::Std;
use Debian::Edu;

sub usage {
    my $retval = shift;
    print <<EOF;
debian-edu-ldapserver [-dfrk] [-b [-s <servername>]]

Find LDAP server and base.  By default the LDAP server is located
using SRV records, and if -b is used, the LDAP base is printed.  If -b
is not used, the LDAP server is used instead.

 -b             Print LDAP base.
 -d             Enable debug output.
 -f             Provide fallback values if dynamic detection fail.
 -k             Print Kerberos server name.
 -r             Print Kerberos realm name.
 -s <server>    Use this server when finding LDAP base.

EOF
    exit $retval;
}

my %opts;
getopts("bdfkrs:", \%opts) || usage(1);

usage(1) if ($opts{s} && !$opts{b});

my $defaultdnsdomain = 'intern';
my $defaultldapserver = 'ldap.intern';
my $defaultldapbase = 'dc=skole,dc=skolelinux,dc=no';
my $defaultkrbserver = 'kerberos.intern';
my $defaultkrbrealm = 'INTERN';

my $dnsdomain;
my $ldapserver;
my $ldapbase;
my $krbserver;
my $krbrealm;

# During installation on the Main Server, dynamic lookup is not
# possible because DNS and LDAP is not yet operational.
if (on_main_server() && during_installation()) {
    my $dnsdomain = $defaultdnsdomain;
    $ldapserver = $defaultldapserver;
    $ldapbase = $defaultldapbase;
    $krbserver = $defaultkrbserver;
    $krbrealm = $defaultkrbrealm;
} else {
    my $hostname = `hostname`;
    chomp $hostname;
    if ("localhost" ne $hostname) {
        $dnsdomain = `LC_ALL=C dnsdomainname 2>/dev/null`;
        chomp $dnsdomain;
        if ("" eq $dnsdomain) {
            # Fall back to fetching from /etc/resolv.conf
            $dnsdomain = dns_resolv_domain();
            print STDERR "warning: no DNS name from dnsdomainname call.  using $dnsdomain from /etc/resolv.conf.\n" if $opts{d};
        }
        $ldapserver = $opts{s} || find_ldap_server($dnsdomain);
        print STDERR "info: found ldap server $ldapserver\n" if $opts{d};
        $krbserver = find_kerberos_server($dnsdomain);
    }
}

if ($opts{k}) {
    if ($krbserver) {
        print "$krbserver\n";
    } elsif ($opts{f}) {
        print "$defaultkrbserver\n";
    } else {
        exit 1;
    }
} elsif ($opts{r}) {
    $krbrealm = find_kerberos_realm($dnsdomain);
    if ($krbrealm) {
        print "$krbrealm\n";
    } elsif ($opts{f}) {
        print "$defaultkrbrealm\n"
    } else {
        exit 1;
    }
} else {
    if (!$ldapserver) {
        if (0 == system("ping -c2 ldap > /dev/null 2>&1") && !$?) {
            system('logger -t debian-edu-ldapserver "The function \'find_ldap_server\' did not provide a ldap host: Use fallback \'ldap\'."');
            $ldapserver = "ldap";
        } elsif (! $opts{f}) {
            system('logger -t debian-edu-ldapserver "The function \'find_ldap_server\' did not provide a ldap host and fallback \'ldap\' does not work."');
            exit 0;
        }
    }
    if ($opts{b}) {
        $ldapbase = find_ldap_base($ldapserver) if $ldapserver && !$ldapbase;
        if ($ldapbase) {
            print "$ldapbase\n";
        } elsif ($opts{f}) {
            print "$defaultldapbase\n";
        } else {
            exit 1;
        }
    } else {
        if ($ldapserver) {
            print "$ldapserver\n";
        } elsif ($opts{f}) {
            print "$defaultldapserver\n";
        } else {
            exit 1;
        }
    }
}

exit 0;

sub dns_resolv_domain {
    my $retval;
    if (open(my $fh, "<", "/etc/resolv.conf")) {
        while (<$fh>) {
            chomp;
            $retval = $1 if (m/search\s+(\S+)/);
        }
        close $fh;
    }
    return $retval;
}

sub on_main_server {
    my $retval = 0;
    if (open(my $fh, "<", "/etc/debian-edu/config")) {
        while (<$fh>) {
            $retval = 1 if (m/^PROFILE="Main-Server\W/);
        }
        close $fh;
    }
    return $retval;
}

sub during_installation {
    return 1 if ( -e "/sbin/start-stop-daemon.REAL" );
    return 0;
}
