#!/bin/sh
#
# smicache --
#
#	A simple caching method, used by the config file `cache' directive.
#
# Copyright (c) 2001 Frank Strauss, Technical University of Braunschweig.
#
# See the file "LICENSE" for information on usage and redistribution
# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
#
# $Id$
#
# NOTE, that this script relies on wget and getopts
# (shell builtin like in bash or standalone).
#
# NOTE, that smicache has just been an experiment. It is NOT suggested
# to use it in a production environment.
#
# Changes in 0.6: HTTPS URL of the libsmi web site (the former directory
# no longer exists), no default directory in /tmp (symlink attacks),
# module names are checked (no path names), and a module is written to
# the cache only after it has been fetched completely.

WGET=wget
GETOPTS=getopts
VERSION=0.6.0

prefix=https://www.ibr.cs.tu-bs.de/projects/libsmi/smicache.php
dir="${XDG_CACHE_HOME:-$HOME/.cache}/libsmi"



do_version () {
    echo "smicache $VERSION"
}



do_usage () {
    echo "Usage: smicache [-Vh] [-d dir] [-p prefix] mib"
    echo "-V         show version and license information"
    echo "-h         show usage information"
    echo "-d dir     use dir as the caching directory (default: $dir)"
    echo "-p prefix  use prefix as the URL prefix for fetching modules"
    echo "mib        name of the module to be fetched"
}



do_fetch () {
    case "$1" in
	""|-*|.*|*[!A-Za-z0-9._-]*)
	    echo "smicache: invalid module name \`$1'" >&2
	    return 1
	    ;;
    esac
    mkdir -p "$dir" || return 1
    tmp=`mktemp "$dir/.smicache.XXXXXX"` || return 1
    if $WGET -q -e "timestamping = off" -O "$tmp" "${prefix%/}/$1" && [ -s "$tmp" ]; then
	chmod 644 "$tmp"
	mv -f "$tmp" "$dir/$1"
    else
	rm -f "$tmp"
	return 1
    fi
}



while $GETOPTS Vhd:p: c ; do
    case $c in
	d)	dir="$OPTARG"
		;;
	p)	prefix="$OPTARG"
		;;
	h)	do_usage
		exit 0
		;;
	V)	do_version
		exit 0
		;;
	*)	do_usage
		exit 1
		;;
    esac
done

shift `expr $OPTIND - 1`



if [ $# -eq 1 ] ; then
    do_fetch "$1" || exit 1
else 
    do_usage
    exit 1
fi

exit 0
