#!/bin/bash

# This script is Copyright 1997 by Giuliano P Procida
# It is released under the GNU GPL (version 2 or later).

set -e

usage () {
    echo Run this script as $0 [dir]. The optional argument dir
    echo defaults to \"~/vice-getroms-tmp\" .
    echo
    echo This script attempts to download the various ROM images for
    echo the VICE emulators. The system administrator may
    echo choose to install the images for all to use. Individual
    echo users may do so for their own use if the images are not
    echo installed by root.
}

yesno () {
    local response
    while true; do
	echo -n "$@" "[y] "
	read response </dev/tty
	case $response in
	    y*|Y*|"") return 0 ;;
	    n*|N*) return 1 ;;
	    *) echo Please respond with y or n.
	esac
    done
}

noyes () {
    local response
    while true; do
	echo -n "$@" "[n] "
	read response </dev/tty
	case $response in
	    y*|Y*) return 0 ;;
	    n*|N*|"") return 1 ;;
	    *) echo Please respond with y or n.
	esac
    done
}

die () {
    echo "$0: $1"
    exit 1
}

getmethods () {
    for i in wget lynx ftp; do
	METHOD="`which $i`" || true
	if [ -n "$METHOD" ]; then
	    return 0
	fi
    done
    return 1
}

LOCATIONS=3
FTPHOST=(
    "sunsite.unc.edu" \
    "sunsite.doc.ic.ac.uk" \
    "hilfy.magd.cam.ac.uk" \
    )
FTPFILE=(
    "/pub/Linux/system/emulators/commodore/vice-roms.tar.gz" \
    "/pub/Mirrors/sunsite.unc.edu/pub/Linux/system/emulators/commodore/vice-roms.tar.gz" \
    "/pub/archive/c64/vice-roms.tgz" \
    )

md5check () {
    case `md5sum "$1" | sed s,[[:space:]].*$,,` in
	8b9237706f47a9b3498d8f881ef0244d) echo "VIC20/basic";;
	f0587624dcd7685710a8fdb35939617f) echo "VIC20/kernal";;
	ada295382a1f2df772a7e5c5c6f34215) echo "VIC20/dos1541";;
	57af4ae21d4b705c2991d98ed5c1f7b8) echo "C64/basic";;
	39065497630802346bce17963f13c092) echo "C64/kernal";;
	9045f52f153ea6dc3c078b7e2b59808a) echo "PET/kernal3032";;
	c366404941aa4783026db7088429d0ac) echo "PET/kernal4032";;
	aad321f207e3cacade1cd9c9d1d245e8) echo "PET/kernal8032";;
	# three alternative ROMs, not sure which set is correct
	48777d2c63f25a8895164752bc95aacd) echo "PET/kernel3032";;
	322bf5b0385e029c114b1931eb39c85a) echo "PET/kernel4032";;
	4abcc40cb3c7fb07980ede4989d0fda5) echo "PET/kernel8032";;
	d41d8cd98f00b204e9800998ecf8427e) echo "empty";;
	f02e326f800ee26f04df7961adbf7c0a) echo "dummy";;
	*)                                echo "unknown";;
    esac
}

show () {
    local dir
    dir="$1"
    ( cd "$dir"
      find -type f -not -name "*.distrib" | ( while read name; do echo -n "${name}"; echo -ne ":\t"; md5check "$name"; done )
    )
}

showcurrent () {
    if [ -d "$INSTALLDIR" ]; then
	echo Currently installed images in $INSTALLDIR:
	show "$INSTALLDIR"
    fi
}

shownew () {
    echo Images available in $BASE:
    show "$BASE"
}

unpackarchive () {
    while true; do
	case "`file rom-images`" in
	    *compressed*) zcat rom-images > rom-images.tmp && \
			  mv rom-images.tmp rom-images || return 1 ;;
	    *tar*)        tar xf rom-images; return ;;
	    *zip*)        unzip rom-images; return ;;
	    *)            echo unrecognised archive; return 1
	esac
    done
}

getarchive () {
    local index
    index=0
    while [ $index -lt $LOCATIONS ]; do
	echo $index ${FTPHOST[$index]} ${FTPFILE[$index]}
	index=$[1+$index]
    done

    echo "[Stick with hilfy for now, the others are currently missing the 1541 ROM.]"
    echo -n "Please select a number of ftp sites (by number and in order of preference): "
    local sites
    read -a sites

    local pass
    pass="`whoami`@`hostname -f`"

    index=0
    local host
    local file
    while [ -n "${sites[$index]}" ]; do
	host=${FTPHOST[${sites[$index]}]}
	file=${FTPFILE[${sites[$index]}]}
	echo trying: $host $file
	case $METHOD in
	    *wget) $METHOD -q -O - ftp://${host}${file} >rom-images || true ;;
	    *lynx) $METHOD -dump ftp://${host}${file} >rom-images 2>/dev/null || true ;;
	    *ftp)  ( $METHOD -n || true ) <<EOF ;;
open $host
user anonymous $pass
bin
get  $file rom-images
quit
EOF
	    *) die "bad method"
	esac
	if [ -s rom-images ] && unpackarchive; then
	    rm rom-images
	    return 0
	fi
	index=$[1+$index]
    done

    return 1
}

installrom () {
    if [ "`whoami`" = root ]; then
	if [ ! -e $2.distrib ]; then
	    dpkg-divert --rename $2 || die "could not divert file: $2"
	fi
    fi
    rm -fr "$2"
    mkdir -p "$2" && rmdir "$2"	|| die "could not clear way for file: $2"
    echo "installing: $1 (as $2)"
    cp "$1" "$2"		|| die "could not install file: $2"
    chmod 644 "$2"		|| die "could not change mode of file: $2"
}

installroms () {
    local ask
    ask=0
    yesno "Would you like to install all recognised ROM images in $INSTALLDIR? Answer n to select only some." || ask=1
    find -type f | (
	local=md
	md=""
	while if [ "$md" = VIC20/dos1541 ]; then md=C64/dos1541; else read name && md=`md5check "$name"`; fi do
	    case "$md" in
		*/*) if test -e "$INSTALLDIR/$md" && cmp -s "$name" "$INSTALLDIR/$md"; then
			echo "skipping: $name (already installed as $md)"
		    else
			if [ $ask -eq 0 ] || yesno "install $name as $INSTALLDIR/$md ?"; then
			    installrom "$name" "$INSTALLDIR/$md"
			fi
		    fi ;;
		dummy)   echo "skipping: $name (a dummy ROM image)" ;;
		unknown) echo "skipping: $name (unrecognised)" ;;
		empty)   echo "skipping: $name (empty)" ;;
	    esac
	done
    )
}

removerom () {
    if [ "`whoami`" = root ]; then
	if [ -e "$1.distrib" ]; then
	    rm "$1"                            || die "could not remove file: $1"
	    dpkg-divert --remove --rename "$1" || die "could not undivert file: $1"
	else
	    echo "Bad dummy ROM image $2, contact maintainer"
	fi
    else
	echo deleting: $1
	rm "$1" || die "could not delete $1"
    fi
}

removeroms () {
    noyes "Would you like to remove any ROM images from $INSTALLDIR?" || return 0
    local ask
    ask=0
    noyes "Would you like to remove all recognised ROM images from $INSTALLDIR? Answer n to select only some." || ask=1
    find $INSTALLDIR -type f | (
	local=md
	while read name; do
	    if [ "${name:${#name}-8}" = ".distrib" ]; then continue; fi
	    md=`md5check "$name"`
	    case "$md" in
		*/*)    if [ $ask -eq 0 ] || noyes "delete $name ?"; then
			    removerom "$name"
			fi ;;
		dummy)   echo "skipping: $name (a dummy ROM image)" ;;
		unknown) echo "skipping: $name (unrecognised)" ;;
		empty)   echo "skipping: $name (empty)" ;;
	    esac
	done
    )
}

# program start

case $# in
    0) BASE="$HOME/vice-getroms-tmp" ;;
    1) case "$1" in
	   -h|-?|--help) usage
		         exit 0 ;;
	   *) BASE="$1" ;;
       esac ;;
    *) usage
       exit 1 ;;
esac

INSTALLDIR=$HOME/lib/vice
if [ "`whoami`" = root ]; then
    INSTALLDIR=/usr/lib/vice
fi

showcurrent

if [ -d $INSTALLDIR ]; then
    removeroms
    ( find $INSTALLDIR -type d -empty | xargs -i rmdir "{}" ) || true
fi

if yesno "Would you like to try and install some ROM images?"; then

    if [ -d "$BASE" ]; then
	if yesno "May I delete and re-create the directory \"$INSTALLDIR\" ?"; then
	    rm -fr -- "$BASE" || die "Could not delete directory $BASE"
	    mkdir -- "$BASE" || die "Could not create directory $BASE"
	else
	    die "aborting"
	fi
    else
	if [ -e "$BASE" ]; then
	    die "$BASE exists and is not a directory"
	fi
	if yesno "May I create the directory \"$BASE\" ?"; then
	    mkdir -p -- "$BASE" || die "Could not create directory $BASE"
	else
	    die "aborting"
	fi
    fi

    cd "$BASE" || die "Could not change directory to $BASE."

    echo Using temporary directory: $BASE

    getmethods || die "Could not find a means of downloading images.\nTry installing wget, lynx or ftp (netstd)."

    echo Using "$METHOD" to download files

    getarchive || die "Could not download the ROM images."

    shownew

    if [ "`whoami`" != root ]; then
	if [ ! -d "$INSTALLDIR" ]; then
	    if [ -e "$INSTALLDIR" ]; then
		die "$INSTALLDIR exists and is not a directory"
	    fi
	    if yesno "May I create the directory \"$INSTALLDIR\" ?"; then
		mkdir -p -- "$INSTALLDIR" || die "Could not create directory $INSTALLDIR"
	    else
		die "aborting"
	    fi
	fi
    fi
    
    installroms

    cd -

    if yesno "Remove temporary directory $BASE ?"; then
	rm -fr $BASE
    fi

fi

echo Finished.

if [ "`whoami`" != root -a -d "$INSTALLDIR" -a ! -f "$HOME/.vicerc" ]; then
    echo You will have to create a $HOME/.vicerc file to make use of
    echo any images stored under $INSTALLDIR. Please consult the
    echo VICE documentation for information on how to achieve this.
fi

exit 0
