#! /bin/sh

RECOVER=/usr/lib/games/slashem/recover-helper

test -x $RECOVER || exit 0

cd /var/games/slashem || exit 1

set -e
case "$1" in
  start)
    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 slashem files.
        if [ "xroot" = "x$owner" ]; then
          echo "Ignoring root's Slash'EM unrecovered save file."
        else 
	  echo "Recovering Slash'EM 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/slashem/recover-helper 
        fi
      fi
    done

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



