#!/bin/sh

# Nethack save-file recovery script for Debian
#
# Ben Gertzfield (che@debian.org) 29 July 1997
# Copyright 1997 Ben Gertzfield. This script is released under the
# GNU General Public License, version 2 or later.

PATH=/bin:/usr/bin:/sbin:/usr/sbin

GAMEDIR=/var/games/nethack

set -e

cd $GAMEDIR

case "$1" in
  start)
    # Has the nethack package been removed?
    test -x /usr/lib/games/nethack/recover-helper || exit 0

    for file in *.0; do

    # Note "$file" is always explicitly quoted to avoid attack.
    # If there are no files, then "$file" = "*.0", which doesn't
    # exist, so we skip once through this loop and exit.
    # Also, the way this is written, some of the files may
    # disappear before we look at them.

    # Also check -L--there shouldn't be any symlinks, but if there
    # are, we aren't going to process them.

    if [ -f "$file" ] && [ ! -L "$file" ]; then
      # Use 'find' to reliably determine the file's owner user name.
      owner="$(find "$file" -maxdepth 0 -printf '%u')"

      # Refuse to recover root's nethack files.
      if [ "xroot" = "x$owner" ]; then
	echo "Ignoring root's Nethack unrecovered save file."
      else 
	echo "Recovering Nethack save files owned by $owner: "

	# "$owner" is explicitly quoted to avoid attack.
	# In particular, if the "find" command above fails,
	# so will the 'su' command below.

	# There really isn't a good safe way to pass a filename to
	# a child shell through 'su -c', so instead we use a helper
	# script running as the user which recovers everything
	# owned by that user.  This avoids the issue of quoting
	# filenames passed through the shell entirely.

	su "$owner" -c /usr/lib/games/nethack/recover-helper 
      fi
    fi

    done
    ;;
  stop|reload|restart|force-reload)
    ;;
  *)
    N=/etc/init.d/nethack 
    echo "Usage: $N {start|stop|restart|force-reload}" >&2
    exit 1
    ;;
esac
