#!/usr/bin/perl
# Filename:	mail_editor
# Author:	David Ljung Madison <DaveSource.com>
# See License:	http://MarginalHacks.com/License
# Description:	Creates a random signature
#
# Just make this your mail editor and then make sure your mail
# program has no signature, just line dashes so the end of the
# file is just '--'
use strict;

##################################################
# Setup the variables
##################################################
my ($PROGNAME,$BASENAME) = ($0,$0);
($MAIN::PROGNAME = $0) =~ s|^.*/||;
$MAIN::BASENAME = $0 =~ m|/| ? $0 : "./$0";
$MAIN::BASENAME =~ s|/[^\/]+$||;
$MAIN::BASENAME=$MAIN::BASENAME ? $MAIN::BASENAME : "/";

# Get the language module
require "$MAIN::BASENAME/sig.pm";

##################################################
# MAIN
##################################################
sub main {
	my $editor=$ENV{EDITOR};
	$editor="vi" if (!$editor);

	my $file="$ARGV[0]";
	slow_death("No file argument!") if(!$file);
	my $file2="${file}.2";

	#########################
	# Make the new temp file
	#########################
	open(FILE2,">$file2") || slow_death("Couldn't open file: $file2");

	#########################
	# Copy the file over to file2, skipping the last line if it is "--"
	#########################
	my $last_line;
	while(<>) {
		print FILE2 "$last_line" if(defined($last_line));
		$last_line=$_;
	}
	#########################
	# If the last line is "--" we add a name and a sig
	#########################
	if ($last_line =~ /^--$/) {
		print FILE2 "\n", pick_name(), "\n\n", get_sig();
	} else {
		print FILE2 $last_line;
	}

	#########################
	# Put the new file where the old is
	#########################
	close(FILE2);
	system("/bin/mv -f $file2 $file");
	slow_death("Couldn't write to $file") if($?);

	#########################
	# Edit the file
	#########################
	system("$editor $file");
	slow_death("Couldn't edit $file with editor $editor") if($?);
}
main();
