#!/usr/bin/perl
# verify.pl : Check clearsigned messages, strip signature
# Action (win32): |perl c:\script\verify.pl|
# Action (unix):  |verify.pl|
# Author: Thorsten Maerz <torte@netztorte.de>
# License: LGPL

use strict;
binmode STDOUT;			# strip CR on WinDos
open(STDERR, ">&STDOUT");	# redir STDERR to STDOUT

my $with_sig_sep=0;		# 0|1 : emit "-- \n" before SIGSTATUS

# ---------------------------------------------------------------------------
# $gpgexe: adjust location/name of gnupg binary

our $gpgexe;
if ($ENV{'COMSPEC'}) { # Win32
  $gpgexe='c:/gnupg/gpg.exe';
} else { # unix
  $gpgexe=`which gpg`;
}
my $gpgcmd="$gpgexe --textmode --logger-fd 1 --verify";
# additional verbosity: --attribute-fd 1 --status-fd 1 --verbose

# ---------------------------------------------------------------------------
# tempfiles - ensure write permission

my $tmp=$ENV{'TEMP'} || $ENV{'TMP'} || $ENV{'TMPDIR'};
my $tempmsg="$tmp/tempmsg.out";
my $tempbody="$tmp/tempbody.out";

# No customizable parts below here ;)
# ===========================================================================
# main - build gpg command

my ($sigbodystart, $sigbody, $sigstart, $sigend);

# ---------------------------------------------------------------------------
# sub:cat() - print file to stdout
sub cat {
  my $filename=shift;
  open IN, "<$filename";
  while (<IN>) { print; }
  close IN;
}

# ---------------------------------------------------------------------------
# read stdin, copy messages for check to $tempmsg, copy stripped body to $tempbody
open TEMPFILE, ">".$tempmsg	|| die("can't open \"$tempmsg\"");
open BODYFILE, ">".$tempbody	|| die("can't open \"$tempbody\"");
while (<>) {
	print TEMPFILE $_ ;
	if (m/-----BEGIN PGP SIGNED MESSAGE-----/) { $sigbodystart=1; }
	if (m/^$/ && ($sigbodystart)) { $sigbody=1; }
	if (m/-----BEGIN PGP SIGNATURE-----/) { $sigstart=1; }
	if (m/-----END PGP SIGNATURE-----/ && ($sigstart)) { $sigend=1; }
	if ($sigbody) {
		if (!$sigstart) {
			s#^- (-.*)#\1#;
			print BODYFILE $_ ; }
		if ($sigbodystart) { $sigbodystart=0; }
	}
}
close BODYFILE ;
close TEMPFILE ;

# ---------------------------------------------------------------------------
# if complete signature, print body and append check result
if ($sigstart) {
	cat($tempbody);
	print "-- \n"	if ($with_sig_sep);
	print "-----PGP SIGNATURE STATUS-----\n";
	open INPIPE, "$gpgcmd $tempmsg |";
	while (<INPIPE>) { s#^gpg: ##; print; }
	close INPIPE;
} else { 
# signature/body not found. return original input.
	cat($tempmsg);
}

# ---------------------------------------------------------------------------
# cleanup
unlink $tempbody ;
unlink $tempmsg ;
