#!/usr/bin/perl
# Copyright (C) 2012 eBox Technologies S.L.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2, as
# published by the Free Software Foundation.
#
# 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 warnings;

use EBox;
use EBox::Global;
use EBox::Sudo;

use File::Slurp;
use EBox::UsersAndGroups::User;
use EBox::UsersAndGroups::Group;

use Error qw(:try);

my $csvFile;
my $verbose;
foreach my $arg (@ARGV) {
    if ($arg eq '-v') {
        $verbose = 1;
    } else {
        if (not $csvFile) {
            $csvFile = $arg;
        } else {
            argError("Unknown argument supplied $arg");
        }
    }
}
$csvFile or argError('No dump file specified');


EBox::init();

if (not defined $csvFile) {
    _error("Not dump file supplied");
} elsif (not -e $csvFile) {
    _error("File $csvFile does not exists");
} elsif (not -r $csvFile) {
    _error("File $csvFile is not readable");
}

my $usersMod = EBox::Global->getInstance()->modInstance('users');
if (not $usersMod) {
    _error("User and group  module is not installed");
} elsif (not $usersMod->isEnabled()) {
    _error("Users and groups module not enabled. Enable it and try again");
}

my %passwords;
my @lines  = File::Slurp::read_file($csvFile);
foreach my $line (@lines) {
    chomp $line;
    if ($line =~ m/^\s*$/) {
        next;
    }
    my @fields = split ',', $line;
    my $type = shift @fields;
    $type or next;
    if ($type eq 'user') {
        try {
            _addUser(@fields);
        } otherwise {
            my ($ex) = @_;
            print "Error adding user with parameters @fields:\n$ex\n";
        };
    } elsif ($type eq 'group') {
        try {
            _addGroup(@fields);
        } otherwise {
            my ($ex) = @_;
            print "Error adding group with parameters @fields:\n$ex\n";
        };
    } else {
        print "Line of unknown type: $type\n";
    }
}

sub _addUser
{
    my ($user,
        $password,
        $fullName,
        $surName,
        $givenName,
        $description,
        $quota) = @_;

    my $userHash = {
        user => $user,
        password => $password,
        fullname => $fullName,
        givenname => $givenName,
        surname   => $surName,
        comment => $description,

    };

    my $userObj = EBox::UsersAndGroups::User->create($userHash);
    if ($verbose) {
        print "Created user $user\n";
    }

    my $changed;
    if ($userObj->get('quota') != $quota) {
        $userObj->set(quota => $quota);
        $changed = 1;
    }

    if ($changed) {
        $userObj->save();
    }

}

sub _addGroup
{
    my ($group, $description, $usersStr) = @_;

    my $groupObj = EBox::UsersAndGroups::Group->create($group, $description);
    print "Group $group added\n" if $verbose;

    my @userNames;
    if ($usersStr) {
        @userNames = split ':', $usersStr if $usersStr;
    }
    if (@userNames) {
        foreach my $userName (@userNames) {
            my $user = EBox::UsersAndGroups::User->new(uid => $userName);
            $groupObj->addMember($user, 1);
        }

        $groupObj->save();
        print "Users added to group @userNames\n" if $verbose;
    }
}

sub argError
{
    my ($err) = @_;

    print "$err\n" if $err;
    print "Usage:\n";
    print "\t$0 [-v] DUMP_FILE\n";
    exit 1;
}

sub _error
{
    my ($err) = @_;

    print "$err\n";
    exit 1;
}

1;