#!/bin/bash
#
# Copyright 2016 Red Hat, Inc.
#
# NAME
#     rht-spawn - log and run command in the background
#
# SYNOPSIS
#     rht-spawn "command to run in background"
#
# DESCRIPTION
#     This tool will generate a temporary script file that contains
#     a wget to register the start and finish of the passed command
#     all executed in the background.
#
# CHANGELOG
#   * Wed Jul 13 2016 Robert Locke <rlocke@redhat.com>
#   - change timespec from now to now + 1 minutes
#   * Sun Feb  7 2016 Robert Locke <rlocke@redhat.com>
#   - add support for galaxyX
#   * Mon Jul  6 2015 Robert Locke <rlocke@redhat.com>
#   - original code

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

# Source some variables that we need - should provide:
# RHT_ENROLLMENT=X
source /etc/rht
# Validate
if [[ -z "${RHT_ENROLLMENT}" ]]; then
  echo "Error: missing a needed variable from /etc/rht"
  echo "RHT_ENROLLMENT = '${RHT_ENROLLMENT}'"
  exit 2
fi

# Additional functions for this shell script
function print_usage {
cat << EOF

This utility spawns and logs commands in the background.

Usage: rht-spawn "command to run"
       rht-spawn -h|--help

EOF
}

# Parse/confirm argument passed
ARGS=$(getopt -o h -l "help" -n "rht-spawn" -- "$@")
if [[ $? -ne 0 ]]; then
  print_usage
  exit 1
fi
eval set -- "${ARGS}"
while true ; do
  case $1 in
    -h|--help)
      print_usage ; exit 0 ;;
    --)
      shift ; break ;;
    *)
      echo "Error: bad option, $1" ; print_usage ; exit 1 ;;
  esac
done

cmdtospawn=$*
if [[ -z "${cmdtospawn}" ]]; then
  print_usage
  exit 5
fi

# Define scriptname
scriptname=/tmp/rht-spawn-$(date +%Y%m%d%H%M%S)
loggingcmd="wget -O ${scriptname} http://foundation0.ilt.example.com/cgi-bin/register.sh?ucfname=$(hostname)\&msg="

# Create scriptname
cat > ${scriptname}.sh <<-EOF
#!/bin/bash

${loggingcmd}"Spawned ${cmdtospawn}"

${cmdtospawn}

if [[ $? -eq 0 ]]; then
  ${loggingcmd}"Completed ${cmdtospawn}"
else
  ${loggingcmd}"Failed ${cmdtospawn}"
fi

EOF
chmod +x ${scriptname}.sh

# Spawn scriptname
at -f ${scriptname}.sh now + 1 minutes

