#!/usr/bin/perl -w
#
use English;
use Getopt::Std;
use strict;

use IO::File;

# Drag in path stuff so we can find emulab stuff.
BEGIN { require "/etc/emulab/paths.pm"; import emulabpaths; }

# Only root.
if ($EUID != 0) {
    die("*** $0:\n".
	"    Must be root to run this script!\n");
}

# Script specific goo.
#
# These go in /var/emulab. Good for all environments!
# 
my $PASSDB   = "$VARDIR/db/passdb";
my $GROUPDB  = "$VARDIR/db/groupdb";

#
# Load the OS independent support library. It will load the OS dependent
# library and initialize itself. 
# 
use libsetup;
use liblocsetup;
use libtmcc;
use librc;


# The old accounts output will be in /usr/local/federation/etc/old_accts and
# the new stuff in /usr/local/federation/etc/accts this is exactly the output
# of tmcc accounts under the local (old) and federated (new) testbed.  We
# delete all the stuff from the old and add all the stuff from the new.

my $old_accts = "/usr/local/federation/etc/old_accts";
my $accts = "/usr/local/federation/etc/userconf";

fatal("Need both $old_accts and $accts") unless -e $old_accts && -e $accts;

my $old = new IO::File $old_accts;
my $n = new IO::File $accts;

fatal("Cannot open $old_accts for reading") unless $old;
fatal("Cannot open $accts for reading") unless $n;

my @delgroups;
my @delusers;

while (<$old>) {
    /^ADDGROUP NAME=([-\w]+)\s+GID=(\d+)/ && do {
	push(@delgroups, $1);
	next;
    };
    /^ADDUSER LOGIN=([-\w]+)/ && do {
	push(@delusers, $1);
    };
}
$old->close();

# Now take 'em out

foreach my $u (@delusers) {
    print "Deleting user $u\n";
    os_userdel($u);
}

foreach my $g (@delgroups) {
    print "Deleting group $g\n";
    os_groupdel($g);
}

while (<$n>) {
    /^ADDGROUP NAME=([-\w]+)\s+GID=(\d+)/ && do {
	my ($group, $gid) = ($1, $2);
	print "Adding group $group($gid)\n";
	os_groupadd($group, $gid);
    };
    /^ADDUSER\s+/ && do { 
	my $login;
	my $pswd;
	my $uid;
	my $gid;
	my $root;
	my $name;
	my $hdir;
	my $glist;
	my $serial;
	my $email;
	my $shell;

	/LOGIN=([\S]+)/ && do { $login = $1; }; 
	/PSWD=(\S+)/ && do { $pswd=$1; } ;
	/UID=(\d+)/ && do { $uid = $1; };
	/GID=(\d+)/ && do { $gid = $1; };
	/ROOT=(\d)/ && do { $root = $1; }; 
	/NAME="([^"]*)"/ && do { $name = $1; };
	/HOMEDIR=(\S+)/ && do { $hdir = $1; };
	/GLIST="([^"]*)"/ && do { $glist = $1; }; 
	/SERIAL=(\d+)/ && do { $serial = $1; };
	/EMAIL="([^"]*)"/ && do { $email=$1; };
	/SHELL=(\S+)/ && do { $shell = $1; };

	print "Adding $login $uid $gid\n";
	os_useradd($login, $uid, $gid, $pswd, "$glist", $hdir, $name, 
	    $root, $shell);
	os_mkdir($hdir, "0755") unless -e $hdir;
	next;
    };
}
$n->close();

