#! /bin/bash
#
# once - execute a command once only
# Copyright (C) 2006 Richard Kettlewell
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#
# $Id: once,v 1.1 2006/04/07 08:48:42 richard Exp $

set -e
mode=once
case "$1" in
--clean )
  shift
  mode=clean
  ;;
--clean-all )
  mode=cleanall
  ;;
--help )
  cat <<EOF
once - prompt when a command is re-executed

Usage:
  once --clean COMMAND ...
  once --clean-all
  once COMMAND ...

Options:
  --clean       Forget about COMMAND...
  --clean-all   Forget about all commands

Without any options the command is executed unconditionally the first time.
The second and subsequence times the user is prompted and given the
opportunity to cancel it.
EOF
  exit 0
  ;;
-* )
  echo "FATAL: unknown option '$1'" >&2
  exit 127
  ;;
esac
key="$HOME/.once/`echo "$@" | md5sum | awk '{print $1}'`"
case $mode in
cleanall )
  rm -rf "$HOME/.once"
  ;;
clean )
  rm -f "$key"
  ;;
once )
  if [ -e "$key" ]; then
    echo "Really run command '" "$@" "'? (y/n)" >&2
    read answer
    case "$answer" in
    y | yes | Y | Yes | YES )
      ;;
    * )
      echo "CANCELLED" >&2
      exit 127
      ;;
    esac
  else
    mkdir -m 0700 -p "$HOME/.once"
    touch "$key"
  fi
  exec "$@" 
  ;;
esac
