#!/bin/sh
# --------------------------------------------------------------------------
#
#              //===//   //=====   //===//   //       //   //===//
#             //    //  //        //    //  //       //   //    //
#            //===//   //=====   //===//   //       //   //===<<
#           //   \\         //  //        //       //   //    //
#          //     \\  =====//  //        //=====  //   //===//   Version III
#
# ------------- An Efficient RSerPool Prototype Implementation -------------
#
# Copyright (C) 2002-2023 by Thomas Dreibholz
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
#
# Contact: thomas.dreibholz@gmail.com


# ====== Warning message when no keyring is configured ======================
display_keyring_warning ()
{
   echo "######################################################################"
   echo "WARNING: Skipping verification; you should better configure a keyring!"
   echo "######################################################################"
}

# ====== Preparation ========================================================
if [ $# -lt 1 ] ; then
   echo >2 "Usage: scriptingcontrol {check-environment [Directory] [Environment] [Keyring] [Trust DB]} {run [Directory] [Input] [Output] [Status] [Environment] [Keyring] [Trust DB]} {cleanup [Directory] [PID] {keeptempdirs}}"
   exit 1
fi
MODE="$1"


# ====== Environment check mode =============================================
if [ "$MODE" = "check-environment" ] ; then
   if [ $# -lt 5 ] ; then
     echo >2 "Usage: scriptingcontrol check-environment [Directory] [Environment] [Keyring] [Trust DB]"
     exit 1
   fi
   DIRECTORY="$2"
   ENVIRONMENT_NAME="$3"
   KEYRING="$4"
   TRUSTDB="$5"

   cd $DIRECTORY || exit 1

   # ====== Verify input ====================================================
   if [ "$KEYRING" != "" -a "$TRUSTDB" != "" ] ; then
      cp -f "$KEYRING" keyring.gpg
      cp -f "$TRUSTDB" trustdb.gpg
      gpg -q --no-default-keyring --keyring ./keyring.gpg --trustdb-name ./trustdb.gpg --homedir . --verify $ENVIRONMENT_NAME || exit 1
   else
      display_keyring_warning
   fi


# ====== Work mode ==========================================================
elif [ "$MODE" = "run" ] ; then
   if [ $# -lt 5 ] ; then
     echo >2 "Usage: scriptingcontrol run [Directory] [Input] [Output] [Status] [Environment] [Keyring] [Trust DB]"
     exit 1
   fi
   DIRECTORY="$2"
   INPUT_NAME="$3"
   OUTPUT_NAME="$4"
   STATUS_NAME="$5"
   ENVIRONMENT_NAME="$6"
   KEYRING="$7"
   TRUSTDB="$8"

   cd $DIRECTORY || exit 1

   # ====== Verify input =================================================
   if [ "$KEYRING" != "" -a "$TRUSTDB" != "" ] ; then
      cp -f "$KEYRING" keyring.gpg
      cp -f "$TRUSTDB" trustdb.gpg
      gpg -q --no-default-keyring --keyring ./keyring.gpg --trustdb-name ./trustdb.gpg --homedir . --decrypt --output $INPUT_NAME.decrypt $INPUT_NAME || exit 1
      mv $INPUT_NAME.decrypt $INPUT_NAME
   else
      display_keyring_warning
   fi

   # ====== Extract input ===================================================
   # Extract the input file:
   # - First, try plain Tar
   # - If it does not work, try Tar/GZip
   # - If it does not work, try Tar/BZip2
   # - If it does not work, return an error
   tar xf $INPUT_NAME || tar xzf $INPUT_NAME || tar xjf $INPUT_NAME || exit 1

   # ====== Do the actual work ==============================================
   chmod 700 ssrun && \
   ./ssrun $OUTPUT_NAME "$ENVIRONMENT_NAME" "$KEYRING" "$TRUSTDB" || exit 1


# ====== Clean up directory =================================================
elif [ "$MODE" = "cleanup" ] ; then
   if [ $# -lt 3 ] ; then
     echo >2 "Usage: scriptingcontrol cleanup [Directory] [PID] {keeptempdirs}"
     exit 1
   fi
   DIRECTORY="$2"
   PID="$3"
   KEEPTEMPDIRS="$4"

   # ------ Send SIGKILL to worker process and all of its childs ------------
   if [ $PID -ne 0 ] ; then
      CHILD_PIDS=""
      find_child_pids() {
         for pid in `pgrep -P $1` ; do
            CHILD_PIDS="$CHILD_PIDS $pid"
            find_child_pids $pid
         done
      }
      find_child_pids $PID

      echo "Terminating$CHILD_PIDS $PID ..."
      kill -KILL $CHILD_PIDS $PID
   fi

   # ------ Remove temporary directory --------------------------------------
   if [ "$KEEPTEMPDIRS" != "keeptempdirs" ] ; then
      rm -rf "$DIRECTORY"
   fi


# ====== Bad mode ===========================================================
else
   echo "ERROR: Bad mode setting $MODE!"
   exit 1
fi

exit 0
