# Raph's shell common functions -*- shell-script -*-
# Copyright (c) 2015 Raphaël Halimi <raphael.halimi@gmail.com>
# Licence: GPL-3+

# Summary:
#
# root_only			abort if user is not root
# lock_script			create lock file
# unlock_script			delete lock file (should be trapped on exit)
# print_error <message>		print message on STDERR with prefix [ERROR]
# print_verbose <message>	print message only ini verbose mode
# delete_files <file...>	delete files
# on_abort			gracefully abort script
#
# Traps signals 2, 13 and 15

root_only () {
  if [ "$(id -u)" != "0" ] ; then
    print_error "This script must be run as root, aborting."
    unlock_script
    exit 1
  fi
}


lock_script () {
  local LOCK_FILE
  LOCK_FILE="/run/lock/`basename $0`.pid"
  if [ -e "$LOCK_FILE" ] ; then
    ps `cat "$LOCK_FILE"` > /dev/null
    if [ $? -ne 0 ] ; then
      printf "Deleting stale lock file %s\n" "$LOCK_FILE"
      rm -f "$LOCK_FILE"
    else
      print_error "Script already running with PID `cat "$LOCK_FILE"`, aborting."
      exit 1
    fi
  fi
  print_verbose "Creating lock file $LOCK_FILE with PID $$"
  echo $$ > "$LOCK_FILE"
}


unlock_script () {
  local LOCK_FILE
  LOCK_FILE="/run/lock/`basename $0`.pid"
  if [ -e "$LOCK_FILE" ] ; then
    if [ `cat $LOCK_FILE` -eq $$ ] ; then
      print_verbose "Deleting lock file $LOCK_FILE with PID $$"
      rm -f "$LOCK_FILE"
    fi
  fi
}


print_error () {
  printf "[ERROR] %s\n" "$1" 1>&2
}


print_verbose () {
  [ $VERBOSE -eq 1 ] && printf "[INFO] %s\n" "$1"
}


delete_files () {
  local FILE_TO_DELETE
  print_verbose "Deleting file(s): $@"
  for FILE_TO_DELETE in "$@" ; do
    print_verbose "Deleting $FILE_TO_DELETE..."
    rm -f "$FILE_TO_DELETE" || print_error "Couldn't delete file $FILE_TO_DELETE"
  done
}


on_exit () {
  true
}

on_abort () {
  print_error "$1, gracefully aborting..."
  on_exit
  exit 1
}


#
# Traps
#

trap 'on_abort "SIGINT caught (interrupt from keyboard)"' 2
trap 'on_abort "SIGPIPE caught (write to pipe with no readers)"' 13
trap 'on_abort "SIGTERM caught (termination signal)"' 15
trap 'unlock_script' 0


#
# Verbosity
#

VERBOSE=0
DEBUG=0


#
# EXAMPLES
#

#
# Print help
#

#print_help () {
#  printf "Usage: %s [OPTIONS] ARG1 ARG2 ARGS...\n" "`basename $0`"
#  printf "ARG1: foo, bar\n"
#  printf "ARG2: bar, foo\n"
#  printf "\nOPTIONS:\n"
#  printf " -d\tdebug mode \n"
#  printf " -v\tverbose mode\n"
#  printf " -h\tprint this help message\n"
#  printf "\nNote : additional note.\n"
#}


#
# Options processing
#

#while getopts "dvh" OPTION ; do
#  case $OPTION in
#    d) set -x ;;
#    v) VERBOSE=1 ; print_verbose "Verbose mode enabled" ;;
#    h) print_help ; unlock_script ; exit 0 ;;
#    *) print_help ; unlock_script ; exit 1 ;;
#  esac
#done ; shift $(($OPTIND-1))

#[ $VERBOSE -eq 1 ] && ...
