#!/usr/bin/env perl
# This script reads from automount maps (local file + nis) and generates an LDIF
use strict;
use warnings;
use diagnostics;
use vars qw($fh);

# Doesn't work
#my ($dir) = $0 =~ m/^(.*)\/.*?$/;
#print "$0 --> $dir\n";
use lib "./perl/lib"; # because it's not really installed
use lib "./lib"; # because it's not really installed
use Net::LDAP::Util;

sub nismap ($$) {
	my ($type, $map) = @_;
	
	print $fh join "\n",
		"dn: nismapname=$map,dc=catnip",
		#"dn: ou=$map,dc=catnip",
		'objectClass: top',
		'objectClass: nismap',
		#"objectClass: $type", # type varies for the real automap and the sub-maps
		"nisMapName: $map",
		#"ou: $map",
		'', '';
}

sub nisobj ($$$) {
	my ($map, $entry, $target) = @_;
	
	print $fh join "\n",
		"dn: nismapname=$entry,nismapname=$map,dc=catnip",
		#"dn: cn=$entry,ou=$map,dc=catnip",
		'objectClass: top',
		'objectClass: nisobject',
		#'objectClass: automount',
		"cn: $entry",
		"nisMapName: $entry",
		"nisMapEntry: $target",
		#"automountInformation: $target",
		'', '';
}


# Get filehandle for LDIF output
#unless ($ARGV[0]) {
#	print STDERR "$0: Usage: `$0 outputfile`\n";
#	exit 1;
#}
#open($fh, ">", $ARGV[0]) or die "Couldn't open '$ARGV[0]' for output";
$fh = *STDOUT;


# Get auto_master to start us off
nismap('automountMap', 'auto_master');
my @files;

open(MASTER, "<", '/etc/auto_master') or die "Couldn't open /etc/auto_master for input";
while (my $line = <MASTER>) {
	chomp $line;
	next if $line =~ m/^\s*#/; # ignore comments
	next if $line =~ m/^\/-/; # ignore /- for now
	
	my ($mount_point, $map, $args) = $line =~ m/(\S+)\s+(\S+)\s+(\S+)/;
	# What to do with $args?
	nisobj('auto_master', $mount_point,
		"ldap:sting.cat.pdx.edu:ou=$map,ou=automounter,dc=catnip --timeout 60");
	
	push @files, $map;
}
close MASTER;

# Recurse
print $fh join "\n",
	"dn: ou=automounter,dc=catnip",
	'objectClass: top',
	"objectClass: organizationalUnit",
	"ou: automounter",
	'', '';
	
foreach my $map (@files) {
	my @file = `ypcat -k $map`;
	
	# Make the map itself
	nismap('organizationalUnit', $map.',ou=automounter');
	
	# Make each entry in the map
	foreach my $line (@file) {
		chomp $line;
		my ($entry, $flags_host) = $line =~ m/(\S+)\s+(.*)/;
		$flags_host =~ s/&$/$entry/; # undo the shorthand notation
		$entry = Net::LDAP::Util::escape_dn_value($entry); # (gtk+)--, (warp2+)--
		nisobj($map.',ou=automounter', $entry, $flags_host);
	}
}
