#!/bin/sh

# Play audio script for ClockChimes

# Copyright 2018 - Stu Miller - Colorado, USA
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# Rewrite cron file and restart cron
#  require: --cron, message, stop, root_user
#  args: $1
#  globals: DEBUG, CRON_FILE, CRON_TXT
#  output: cron file
cron(){
  if [ "$DEBUG" = "yes" ]; then
    message "START $FUNCNAME - input: ARG1:|$1|"
  fi # END debug

  # require root
  root_user $1

  # quote variables to preserve newlines
  # assign tmp as piped conf file contents with stripped clockchimes lines
  local TMP="$(printf "$(<$CRON_FILE)" | grep -v 'clockchimes')"
  # expand escape sequences, append cron text to tmp, write to cron file
  printf "%b" "$TMP\n$CRON_TXT" > "$CRON_FILE"
  # grep to strip comments & blank lines, write to stdout
  message "SAVED $CRON_FILE

list of cronjob lines:
$(grep -v -e '#\|^$' "$CRON_FILE")"

  # restart crond
  killall crond 1>/dev/null
  crond -l notice
  message "crond restarted"

  if [ "$DEBUG" = "yes" ]; then
    message "END $FUNCNAME - output: cron file"
  fi # END debug

  stop 0
} # END cron
