#!/bin/bash
# CGI Interface to the ps2pdf program
# Converts postscript files to PDF format
# 20041213 mas01em@gold.ac.uk

# Institution home page
#TOP_URL=http://www.goldsmiths.ac.uk
#TOP_TEXT="Goldsmiths College Home Page"

# Department home page
#SUB_URL=http://www.doc.gold.ac.uk
#SUB_TEXT="Department of Computing Home Page"

# Author email
MAIL_TO=E.Martin@gold.ac.uk

# Debug mode
DEBUG=false

# Minutes to keep old conversions
FLUSH_MIN=15

# Postscript to PDF filter program
ps2pdf=/usr/bin/ps2pdf

# Conversion log file
LOG_FILE=/var/log/ps2pdf.log

# Directory for temporary files
TEMP_DIR=/var/local/ps2pdf/tmp

# Base output directory for converted files
OUTPUT_DIR=/var/local/ps2pdf/out

# Base URL for links to converted files
OUTPUT_URL=//$SERVER_NAME/ps2pdf

# Links to external resources
RES_CSS=//$SERVER_NAME/it/mcsdb/mcsdb.css
RES_DOT=//$SERVER_NAME/images/dot-purple.jpg
RES_GHOST=//$SERVER_NAME/images/ghost32.gif
#RES_TOPLOGO=//$SERVER_NAME/it/gcaa.gif
#RES_SUBLOGO=//$SERVER_NAME/it/deptlogo.jpg

# Colour scheme
COLOR_LOW="#555588"
COLOR_MID="#AAAAFF"
COLOR_HI="#E0E0FF"
COLOR_VHI="#F0F0FF"

# Write an entry to the logfile
log()
{
  echo `date "+%Y-%m-%d %H:%M:%S|"`"$*" >> $LOG_FILE
}

# Flush all expired conversions and quit
# Call regularly as root from CRON with $1=flush (say every 5 mins)
if [ "$1" = "flush" ]; then
  find "$OUTPUT_DIR" -follow -mindepth 1 -mmin +$FLUSH_MIN -exec rm -rf \{\} \; 2>/dev/null
  exit 0
fi

# Get a link to this script
SELF_URL=//${SERVER_NAME}${SCRIPT_NAME}

# Get output directory for current user
USER_DIR=$OUTPUT_DIR/$REMOTE_ADDR

# Send standard page header
cat <<-HEAD
	Content-Type: text/html

	<html><head><title>Postscript to PDF Document Conversion</title>

	<LINK TYPE="text/css" REL=stylesheet HREF="$RES_CSS">
	</head><body bgcolor="#FFFFFF" text="#000000">

	`/usr/local/bin/getintranetpageheader`

	<h2><a style="text-decoration: none"
	 href="$SELF_URL">Postscript to PDF Document Conversion</a></h2>

	<table border=0 bgcolor="$COLOR_VHI" cellspacing=0 cellpadding=0><tr><td>

	<table border=1 width="100%" cellspacing=1 cellpadding=8
	 bgcolor="$COLOR_MID"><tr><td bgcolor="$COLOR_HI" style="color: $COLOR_LOW">
	<p>A postscript file is created when you choose <em>'print-to-file'</em>
	 using a postscript printer driver.</p>
	<p>This form converts printer-specific postscript files into more portable PDF documents.</p>
	</td></tr></table><br>

	HEAD

# Send the file upload form
cat <<-UPLOAD
	<img border=0 width="100%" height="1" src="$RES_DOT"><br>
	<table border=0 width="100%" cellspacing=0 cellpadding=0><tr><td bgcolor="$COLOR_HI">
	<font size=3 color="$COLOR_LOW"><b>Convert a File</b></font><br>
	</td></tr></table>
	<img border=0 width="100%" height="1" src="$RES_DOT"><br>

	<p>Select a postscript file and click 'Convert'
	 to convert it into a PDF document.</p>
	<table border=1 width="100%" cellspacing=1 cellpadding=4 bgcolor="$COLOR_MID">
	<form method=POST enctype="multipart/form-data">
	<tr><td bgcolor="$COLOR_HI" align=center>
	<b>Postscript File:</b><input type=file name=psdata size=60><br>
	<input type=submit value=Convert style="font-size: 12">
	</td></tr>
	</form>
	</table>
	UPLOAD

# Determine action from content type (if any)
content=`echo $CONTENT_TYPE | cut -d';' -f1 | tr A-Z a-z`
case "$content" in

 multipart/form-data)

  # Process uploaded file

  # Get MIME multipart boundary string
  boundary=`echo $CONTENT_TYPE | sed 's,^.*boundary=,,'`

  # Get a temporary file
  if
    ! TEMPFILE=`mktemp $TEMP_DIR/ps2pdf.XXXXXX`
  then
    log "Cannot create temporary file, aborting"
  else

    # Read all form data from stdin into temporary file
    dd bs=1 count=$CONTENT_LENGTH 2>/dev/null > $TEMPFILE

    # Get original postscript filename from temporary file
    fullname=`grep -i -m 1 "^Content-Disposition: form-data;" $TEMPFILE |
     sed 's,^.*filename=",,;s,".*$,,'`

    # Remove path from original postscript filename
    fname=`echo "$fullname" | sed 's,^.*\\\,,;s,^.*/,,;s,[.][^.]*$,,'`.pdf

    # Valid filename?
    if [ "$fname" != ".pdf" ]
    then

      # Create personal web folder for user (if necessary)
      [ ! -e "$USER_DIR" ] && mkdir "$USER_DIR" && chmod 770 "$USER_DIR"

      # Extract postscript from temporary file and convert to a pdf file
      awk '
        BEGIN{x=0;h=0}
        {
          if (x==0) {
            if (/^--'$boundary'[\r]?$/) x=1
          } else if (x==1) {
            if (/^--'$boundary'--[\r]?$/) { x=2; h=0 }
            else if (h==0) { if (/^[\r]?$/) h=1; }
            else print
          }
        }' $TEMPFILE | $ps2pdf - - > "$USER_DIR/$fname"
      chmod 644 "$USER_DIR/$fname"
      fsize=`stat -c %s "$USER_DIR/$fname"`

      # Log the conversion
      log "$REMOTE_ADDR|$fullname|$CONTENT_LENGTH|$fname|$fsize"

    fi

    # Delete temporary file
    ! $DEBUG && rm -f $TEMPFILE

  fi

  ;;

esac

# Send info about current converted documents
cat <<-DOCS
	<p>Converted documents are stored on the server
	 for $FLUSH_MIN minutes for you to download.</p>

	<img border=0 width="100%" height="1" src="$RES_DOT"><br>
	<table border=0 width="100%" cellspacing=0 cellpadding=0><tr><td bgcolor="$COLOR_HI">
	<font size=3 color="$COLOR_LOW"><b>Converted Documents</b></font>
	</td></tr></table>
	<img border=0 width="100%" height="1" src="$RES_DOT"><br>

	<p>These converted documents have been temporarily saved on the server
	 (most recent first):</p>
	<table border=1 width="100%" cellspacing=1 cellpadding=4 bgcolor="$COLOR_MID">
	<tr><th bgcolor="$COLOR_HI" style="font-size: 12; font-weight: normal">
	 Listing correct as of: `date "+%h %d &nbsp; %H:%M"`</th></tr>
	<tr><td align=center bgcolor="$COLOR_HI">
	<table border=0 width="100%">
	DOCS

# Send links to all converted documents
if [ -d "$USER_DIR" ] && [ `ls "$USER_DIR" 2>/dev/null | wc -l` -gt 0 ]
then
  ls -gGht "$USER_DIR" | grep -v "^total" |
   sed 's,^[^[:space:]]\+[[:space:]]\+[^[:space:]]\+,,' |
   while read size month day time pdf; do
    cat <<-LIST
	<tr>
	<td style="font-size: 14"><li><a target="_blank"
	 href="$OUTPUT_URL/$REMOTE_ADDR/$pdf">$pdf</a></li></td>
	<td>$size</td><td>$month $day &nbsp; $time</td>
	</tr>
	LIST
  done
else
  cat <<-EMPTY
	<tr><td align=center style="font-size: 14">No converted documents</td></tr>
	EMPTY
fi

# Send end of converted documents list and page footer
cat <<-FOOT
	</table>
	</td></tr>
	<form>
	<tr><th bgcolor="$COLOR_HI"><input
	 type=button value="Refresh List"
	 onClick="location.href='$SELF_URL'"></td></tr>
	</table>
	</form>
	<p>To save a permanent copy of a document,
	 right-click on the filename and select 'Save ... As'.</p>

	<img border=0 width="100%" height="1" src="$RES_DOT"><br>

	<table border=0 width="100%" cellspacing=0 cellpadding=0
	 bgcolor="#FFFFFF"><tr><td valign=top>
	<sup>Web Interface: <a href="mailto:$MAIL_TO">$MAIL_TO</a></sup>
	</td><td align=right valign=top>
	<sup>Powered by <a href="http://www.cs.wisc.edu/~ghost/"
	 target="_blank">Ghostscript<img align=top border=0
	 src="$RES_GHOST" alt="Ghostscript Home Page"></a></sup>
	</td></tr></table>

	</td></tr></table>

	</body></html>
	FOOT

### END ###

