#!/usr/bin/perl

use utf8;
use strict;
use warnings;

use Getopt::Long qw(:config no_auto_abbrev);
use DBI;

my %S = ();
GetOptions(\%S,
	'help',
	'passdir=s',
	'add=s',
	'rem=s',
	'list',
) or die("Use --help for usage information.\n");
if(!scalar(keys(%S))) { die("Use --help for usage information.\n"); }

my $BASEDIR = '/home/natura/mex/public';
my @users;

if($S{'help'}) {
	print("Usage:\n");
	print("\tperl managedb.pl [OPTIONS...]\n");
	print("Options:\n");
	print("\t--help\t\t| Show this information.\n");
	print("\t--passdir=\"dir\"\t| Set the directory of the .db file.\n");
	print("\t--add=\"users\"\t| Adds users (separated by ' ').\n");
        print("\t--rem=\"users\"\t| Removes users (separated by ' ').\n");
	print("\t--list\t\t| Shows a list of users.\n");
	exit(0);
}

if($S{'passdir'}) {
	$BASEDIR = $S{'passdir'};
}

my $USRDIR = $BASEDIR."/users";

my @dris = DBI -> available_drivers();
my $driver = '';
for my $dri (@dris) {
	if($dri =~ m/sqlite/i) {
		$driver = $dri;
		last;
	}
}

my $dbfile = $BASEDIR.'/passarola.db';
my $dbh = DBI -> connect("dbi:".$driver.":dbname=".$dbfile,"","",{PrintError=>0,RaiseError=>0})
or die("Error: ".$DBI::errstr."\n");
my $sth;
my $sql;

$dbh -> do('CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        login VARCHAR(255) UNIQUE NOT NULL,
        password TEXT NOT NULL,
        roles TEXT,
        name VARCHAR(255) DEFAULT NULL,
        email VARCHAR(255) DEFAULT NULL
);') or warn("Warning: ".$DBI::errstr."\n");

if($S{'add'}) {
	my @additions = split(" ", $S{'add'});
	for my $addition (@additions) {
		print("Adding user '".$addition."':\t");
		$dbh -> do('INSERT INTO users (login, password, roles) '.
		'VALUES ("'.$addition.'", "'.crypt($addition, 'PA').'", "regular, advanced, admin"'.
		');');
		if(!$DBI::err) {
			print("[o]\n");
		} elsif($DBI::err == 19) {
			print("[x] (Username already exists)\n");
		} else {
			print("[x] (".$DBI::errstr.")\n");
		}
		my $dir = $USRDIR.'/'.$addition;
		if(! -d $dir) { mkdir($dir); }
	}
}

if($S{'rem'}) {
        my @removals = split(" ", $S{'rem'});
        for my $removal (@removals) {
                print("Removing user '".$removal."':\t");
                $dbh -> do('DELETE FROM users WHERE login="'.$removal.'";');
                if(!$DBI::err) {
                        print("[o]\n");
                } else {
                        print("[x] (".$DBI::errstr.")\n");
                }
        }
}

if($S{'list'}) {
        $sth = $dbh -> prepare('SELECT * FROM users;');
        $sth -> execute() or die("Error: ".$DBI::errstr."\n");
	print("Registered users:\n");
	while(my $ref = $sth -> fetchrow_hashref()) {
		print("\t".$ref -> {'id'});
		print(": ".$ref -> {'login'});
		#print(", ".$ref -> {'password'});
		print(", ".$ref -> {'name'}) if $ref -> {'name'};
		print(", ".$ref -> {'email'}) if $ref -> {'email'};
		print("\n");
	}
        $sth -> finish;
}

$dbh -> disconnect();
