#!/bin/sh
#	BSDI	showpicture,v 1.3 1997/06/22 16:10:14 jch Exp
#
# Copyright (c) 1991 Bell Communications Research, Inc. (Bellcore)
# 
# Permission to use, copy, modify, and distribute this material 
# for any purpose and without fee is hereby granted, provided 
# that the above copyright notice and this permission notice 
# appear in all copies, and that the name of Bellcore not be 
# used in advertising or publicity pertaining to this 
# material without the specific, prior written permission 
# of an authorized representative of Bellcore.  BELLCORE 
# MAKES NO REPRESENTATIONS ABOUT THE ACCURACY OR SUITABILITY 
# OF THIS MATERIAL FOR ANY PURPOSE.  IT IS PROVIDED "AS IS", 
# WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
#

unset IFS

# Defaults
METAMAIL_TMPDIR=${METAMAIL_TMPDIR:-${TMPDIR:-/tmp}}
X_VIEWER=${X_VIEWER:-"xv -geometry +0+0 -perfect -2xlimit"}

usage() { echo "Usage: showpicture [-viewer program] [file(s)]" 1>&2; }

cleanup() {
    if [ $# -gt 0 ]; then
    	rc=${1}; shift
    else
	rc=0
    fi
    if [ $# -gt 0 ]; then
	for line; do
	    echo "$(basename ${0}): ${line}"
	done
    fi
    if [ -n "${METAMAIL_TMPDIR}" -a -e "${METAMAIL_TMPDIR}" ]; then
	if [ -n "${TEMPDIR}" -a -e "${TEMPDIR}" ]; then
	    rm -rf "${TEMPDIR}"
	fi
    fi
    exit ${rc}
}

trap "cleanup 1 interrupted" 1 2 15

case "$1" in
    -v*) shift;
	 if [ $# -lt 1 ]; then usage; exit 1; fi
	 X_VIEWER=$1; shift;
	 ;;
esac

if [ $# -eq 0 ]; then
    if [ ! -e "${METAMAIL_TMPDIR}" ]; then
	cleanup 1 "'${METAMAIL_TMPDIR}' does not exist"
    elif [ ! -d "${METAMAIL_TMPDIR}" ]; then
	cleanup 1 "'${METAMAIL_TMPDIR}' is not a directory"
	exit 1
    fi
    TEMPDIR=${METAMAIL_TMPDIR}/showpicture.$$
    mkdir -p -m 0700 "${TEMPDIR}" || cleanup 1
    set "${TEMPDIR}/picture.$$"
    cat > "${1}"
fi

if [ ! "${DISPLAY}" ]; then
    echo ""
    echo This message contains a picture, which can currently only be
    echo viewed when running X11.  If you read this message while running
    echo X11, and have your DISPLAY variable set, you will then
    echo be able to see the picture properly.
    echo ""
    echo "The picture data is saved in:"
    ls -l "${@}"
    # for i in "${@}"; do echo ${i}; done | column
    echo "If you do not want this data, please delete it."
    exit 0
fi

echo "Type into the picture window: space to see next picture, 'q' to quit"
${X_VIEWER} "${@}"
cleanup 0
