#!/usr/bin/perl
#
#	mk_th - themen-bereich fuer die mail-box einrichten
#
# Last Change by DL6RAI: Sat Nov 11 19:59:10 GMT 2000

require "getopts.pl";

if ($#ARGV < 1) {
    printf "Usage: mk_th [-q] th_name type\n";
    exit(1);
}

($clx_user_uid,$clx_user_gid,$home) = (getpwnam('clx_us'))[2,3,7];
$db_name = "clx_db";
$psql = "psql -d $db_name -Aqtc";
($home) = (getpwnam('clx_us'))[7];
$quiet = 0;

die "You must be user clx_us to run $0" if ($< != $clx_user_uid);
die "Postmaster is not running" if (!(`ps auxw | grep postmaster | grep -v grep`));

&Getopts('q');
if (length($opt_q) > 0) {
    $quiet = 1;
}

$name = $ARGV[0];
$type = $ARGV[1];
$dir = "$home/box/$name";

if ($type < 0 || $type > 3) {
    printf "Type $type is incorrect.\n";
    exit(1);
}

if (!(-e "$home/box")) {
    mkdir("$home/box", 0755);
}

$cmd = "select distinct d_name from ml_dir where d_name='$name'";
chop ($result = `$psql \"$cmd\"`);

$x = (-e $dir);
$y = ($result eq $name);

if ($debug) {
    print "result='$result'\n";
    print "name='$name'\n";
    print "x=$x, y=$y\n";
}

if ($x && !$y && $type < 3) {
    print "Directory $dir exists in filesystem but not in database.\n";
    print "This is an unexpected inconsistency.\n";

    @list = `find $dir -type f -print`;
    $n = $#list+1;

    if ($n == 0) {
        print "Empty directory $dir will now be deleted.\n";
    } else {
        foreach $i (@list) {
            print $i
        }
        print "$n files in $dir will be deleted.\n";
        print "Do you want to continue (y/n)? ";
        read(STDIN,$ans,1);
        if ($ans =~ /^n/i) {
            print "OK, please fix this problem problem manually.\n";
            exit 1;
        }
    }
    print "\n";
    print "+ rm -rf $dir\n";
    system "rm -rf $dir";
    print "\n";
}

if ($x && $y) {
    if (! $quiet) {
        print "Cannot create $name.\n"; 
        print "Directory $dir and table $name entry already exist.\n";
    }
    exit(0);
}

if (!$x && $y) {
    print "Database entry $name exists but directory $dir was not found.\n";
    print "This is an unexpected inconsistency.\n";
    print "The entry $name will now be deleted from ml_dir.\n";
    print "\n";
    $cmd = "delete from ml_dir where d_name='$name'";
    print "+ $psql \"$cmd\"\n";
    system "$psql \"$cmd\"";
    print "\n";
}

mkdir("$home/box/$name", 0755) || \
	print "Could not mkdir $home/box/$name, directory already exists.\n";
$cmd = "insert into ml_dir (d_name,d_flag,d_count,d_reorg) 
        values ('$name',$type,0,'now')";
print "+ $psql \"$cmd\"\n";
system "$psql \"$cmd\"";

if ($? == 0) {
	print "Directory $name was added to database.\n";
} else {
	print "Command returned $?, not sure if all went well.\n";
}

exit(0);
