#!/usr/local/bin/perl

# Perl script to post student homework encrypted to a
# public directory. Uses pgp for encryption, and a fixed
# targetUser for the public key. The public key is taken by
# creating .pgp with a copy of the pgpsource pubring.pgp.

# Will create the ~/.pgp and the subdir under public_html,
# if they do not exist.

# NOTE: does not handle .pgp exists but public key for
# targetUser not in .pubring.pgp. Future release should
# check return value of pgp -kv $targetUser and respond
# appropriately. Pgp is really awkward to script.

# (c) 1997 Burt Rosenberg all rights reserved
# 25 Jan 1997

# customize
    $DEBUG = 0==1 ;
    $postdir = "public_html/Math120" ;
    $targetUser = "mth120" ;
    $pgpsource = "/home/escambia/mth120/public_html/.pgp" ;

# check for .pgp directory and create if necessary.
    $pgpdir = $ENV{"HOME"} . "/.pgp" ;
    if ( -e $pgpdir ) {
       if ( $DEBUG ) {
	 printf "pgp directory exists.\n" ;
       }
    }
    else {
       if ( $DEBUG ) {
	 printf "pgp will be created.\n" ;
       }
       system "mkdir $pgpdir" ;
       system "chmod go-rx $pgpdir" ;
       system "cp $pgpsource/* $pgpdir" ;
       system "chmod go-r $pgpdir/*" ;
    }

# check for public_html/$postdir and create if necessary
    $s = $ENV{"HOME"} . "/" . $postdir ;
    if ( -e $s ) {
       if ( $DEBUG ) {
          printf "post directory exists.\n" ;
       }
    }
    else {
       if ( $DEBUG ) {
          printf "post directory will be created.\n" ;
       }      
       system "mkdir $s" ;
       system "chmod a+rx $s" ;
    }
 
# process all arguments
   while ( $filename = shift ) {
      if ( $DEBUG ) {
         printf "Processing %s\n", $filename ;
      }

      # filter out optoins
      if ( $filename =~  /^-/ ) {
         # it's an option.
         if ( $DEBUG ) { printf "   ... option\n" ; }
         next ;
      }
     
      # filter out nonexistant files
      unless ( -e $filename && -f $filename ) {
         printf STDERR "error: %s not found\n", $filename ;
         next ;
      }
     
      # filter out overwritten targets
      $target = $ENV{"HOME"} . "/" . $postdir . "/" . $filename . ".asc" ;
      if ( -e $target ) {
          printf STDERR "error: %s exists.\n", $target ;
          next ;
       }
    
       # and finally ...
       system "pgp -efa $targetUser < $filename > $target" ;
       unless ( -e $target ) {
          printf STDERR "error: %s was not created.\n", $target ;
           next ;
        }
        system "chmod a+r $target" ;
   }
