#!/usr/bin/perl
# What:		xnm
# Author:	David Ljung Madison <DaveSource.com>
# See License:  http://MarginalHacks.com/License
# Description:	Checks for new mail every so often.
#		Starts up a mail window if any mail is found.
# Bugs:		When elm allows editing on the mailbox, it
#		does an update with $tmpbox gone, and then reopens
#		the box.  This is a race that will end up with two
#		mail readers if SLEEP_TIME is low enough and the mailbox
#		is big enough.

use strict;

##################################################
# Setup vars
##################################################
my $SLEEP_TIME=1;
my $mail = $ENV{'MAIL'};
die("Couldn't find mail location (\$mail)\n") if (!$mail);
my $tmpbox = "/tmp/.mbox." . ($ENV{'USER'} ? $ENV{'USER'} : $ENV{'LOGIN'});

my $HEIGHT=50;

##################################################
# Modification times
##################################################
my $me= -M $0;
#my $mod= -M $mail;
my $mod=0;	# Automatically startup mail when xnm is started

##################################################
# Startup an X program to read mail
##################################################
sub start_mailer {
  #########################
  # Check for an existing elm process
  #########################
  return print "  [mailreader open]" if (-f $tmpbox);

  print "  [starting xelm]";
#  system("kvt -no_menubar -no_scrollbar -vt_fg blue -vt_bg white -vt_geometry 80x45 -n xelm -caption $mail -e elm > /dev/null 2>&1 &");
#  system("kvt -restore my_kvts/Mail > /dev/null 2>&1 &");
  my $where= (-f "/tmp/athome") ?
             "-display getdave.com:0 -geometry =80x$HEIGHT+200+50" :
             "-geometry =80x$HEIGHT+450+150";
  system("xterm $where -T Mail -fg blue -bg white +sb -fn fixed -e Elm");
  $mod = -M $mail;	# Ignore any modifications made while reading mail
  # This is a slight race, new mail between the system() and the -M will be lost
  sleep 1;
}

##################################################
# Check for changes to mailbox times
##################################################
sub check_newmail {
  if ($mod != -M $mail) {
    print "[$mail] [",scalar localtime(time),"]  ",
          ($mod ? "New mail" : "Startup") if ($mod);
    start_mailer();
    print "\n"x80;
  }
  # Snifty.  If the script is modified, it restarts itself
  if ($me != -M $0) {
    print "[$0]  Script changed - restarting.  ", (scalar localtime(time)), "\n";
    exec $0,@ARGV;
  }
}

##################################################
# Main loop
##################################################
sub main {
  select((select(STDOUT), $|=1)[0]);
  while(1) {
    check_newmail();
    sleep $SLEEP_TIME;
  }
}

main();
