#!/usr/bin/perl

$mail_dir  = "/home/nwserv.sys/mail/user";
$spoll_dir = "/var/spool/mail";

sub cnm_from_file {
  $number = 0;
  $close  = 0;
  while ( $line = <VSTUP> ) {
    chop ($line);
    if ( $line =~ /^From / ) {
      while ( -e "${mail_dir}/${user_name}/${number}.cnm" ) {
        $number++;
      }
      if ( $close != 0 ) {
        close (VYSTUP);
      } else {
        $close = 1;
      }
      if (! open (VYSTUP, ">${mail_dir}/${user_name}/${number}.cnm") )
      {
        print "nemohu zapsat do souboru
        ${mail_dir}/${user_name}/${number}.cnm\n"; return 1;
      } else {
        print "  vytvarim ${user_name}/${number}.cnm ...\n";
      }
    }
    print VYSTUP "$line\r\n";
  }
  close (VYSTUP);
  return 0;
}

opendir(SPOOL, $spoll_dir) || \
   die "nemohu cist z adresare $spoll_dir";
while ( $user_name = readdir(SPOOL) ) {
  if ( -f "${spoll_dir}/${user_name}" && -s
  "${spoll_dir}/${user_name}") {
    rename ("${spoll_dir}/${user_name}",
    "${spoll_dir}/${user_name}.lock") || \
         die "nemohu prejmenovat soubor ${spoll_dir}/${user_name}";
    open (VSTUP, "${spoll_dir}/${user_name}.lock") || \
         die "nemohu otevrit soubor ${spoll_dir}/${user_name}.lock";
    if ( &cnm_from_file ) {
      close (VSTUP);
      rename ("${spoll_dir}/${user_name}.lock",
      "${spoll_dir}/${user_name}");
    } else {
      close (VSTUP);
      unlink ("${spoll_dir}/${user_name}.lock") || \
           die "nemohu smazat soubor ${spoll_dir}/${user_name}.lock";
    }
  }
}
exit 0;
