#!/usr/bin/perl
#$Id: initialise_passwdfile.pl,v 1.4 2013/01/29 08:34:56 sofc Exp $
use Fcntl qw(:DEFAULT :flock);
use Tie::DataDumper;
use strict;
use warnings;
use AFM;
$! = 1;
print "##########################################\n";
print "### Warning: initialising the password ###\n";
print "### file will erase any prior users!.  ###\n";    
print "##########################################\n";
print "### Proceed?? (yes/no): ";
my $cont = 1;
my $str = '';
while ($cont)
{
    $str = <STDIN>;
    if ($str !~ /Yes|No/i)
    {
	print "\n### Please answer Yes or No: ";
    }
    else
    {
	$cont = 0;
    }
}
if ($str !~ /Yes/i)
{
    print "Ok exiting\n";
    exit;
}
my $newuser = 'root';
my $f = &get_cv('passwds','passwdfile');
my $l = &get_cv('passwds','passwdlock');
sysopen(PFH, $l, O_WRONLY | O_CREAT) or die "Error: can't open file: $l \n $!";
flock(PFH, LOCK_EX);
#### Remove old paswd file if exsist ###
unlink $f if (-e $f);
my $pass = int(999999 + rand(9000000));
my $md5 = crypt($pass,$newuser);
my $email = 'root@localhost';
my $time = time;
tie our @users => 'Tie::DataDumper',$f or die "Could not tie file $f $!\n";
my %p = ('celltest'=>3);
my %h = ('id'=>1,'rid'=>'root','name'=>'Administrator','email'=>$email,'passwd'=>$md5,'admin'=>1,'active'=>1,'lastchange'=>$time,'perm'=>\%p);

push @users,\%h;
tied(@users)->save;

print "##########################################\n";
print "## Root user $newuser created.             ###\n";
print "## Password for user $newuser : $pass    ###\n";
print "##########################################\n";

#### Setting correct owner and permissions on paswd file ###
my ($login,$p,$uid,$gid) = getpwnam('sofc') or die "User sofc not in passwd file, failed setting owner and permissions on $f\n";
chown $uid,$gid,$f;
chmod 0664 , $f;

flock(PFH, LOCK_UN);
close(PFH);
exit;
