#!/usr/bin/perl
#usermod
$|=1;
require 5.004;
require "./preferences.pl";

use Getopt::Std;
getopts('la:m:d:');

$Usage = "\nUsage:\n$0 [-l]\n$0 [-a] [-m] user passwd\n$0 -d user\n\n".
         "-l  List all users\n".
         "-a  Add/Create a new 'user' with the password 'passwd'\n".
         "-m  Modify the 'user' password to 'passwd'\n".
         "-d  Delete 'user'\n";

$UserFile = $Configdir.'/miniserv.users';
open(F, "<$UserFile") or die "\nUnable to locate the miniserv user file: $UserFile\n";
@data = <F>;
close(F);
chomp @data;
foreach (@data) {
  ($u,$crypt) = split /:/;
  $Users{$u} = $crypt;
}

if ($opt_l) {
  &ListUsers();
  exit;
} elsif ($opt_a) {
  $passwd = shift || die $Usage;
  &AddUser($opt_a,$passwd);
} elsif ($opt_m) {
  $passwd = shift || die $Usage;
  &ModUser($opt_m,$passwd);
} elsif ($opt_d) {
  &DelUser($opt_d);
} else {
  die $Usage;
}

print "\nServer Restarted.\n" if &RestartServer();
print "\n";
exit;

sub ListUsers {
  print "\nCurrent users are:\n";
  foreach (sort keys %Users) {
    print "  ",$_,"\n";
  }
}

sub AddUser {
  my($user,$passwd) = @_;
  die "\nUser '$user' already exists, use -m to modify the user.\n" if defined $Users{$user};
  $Users{$user} = crypt($passwd, "XX");
  &WriteUsers();
}

sub ModUser {
  my($user,$passwd) = @_;
  die "\nUser '$user' does not exist, use -a to add the user.\n" unless defined $Users{$user};
  $Users{$user} = crypt($passwd, "XX");
  &WriteUsers();
}

sub DelUser {
  my($user,$passwd) = @_;
  die "\nUser does not exist.\n" unless defined $Users{$user};
  die "\nYou cannot delete the admin user!\n" if $user eq "admin";
  delete $Users{$user};
  &WriteUsers();
}

sub WriteUsers {
  open(F, ">$UserFile") or die "\nUnable to write to the miniserv user file: $UserFile\n";
  foreach (sort keys %Users) {
    print F $_,":",$Users{$_},"\n";
  }
  close(F);
}

sub RestartServer {
  my $pidfile = $Vardir."/miniserv.pid";
  return 0 unless -f $pidfile;
  open(F, "<$pidfile") || return 0;
  my $pid = <F>;
  chomp $pid;
  close(F);
  return kill('HUP', $pid);
}
