#!/bin/bash
#
# sccl_kill_package bricht start eines Paketes im Script-Cluster ab
#
# Aufruf:
#
# sccl_kill [--force] <package> [<pidsig>]
#
########################################################################################
#
. $(dirname $0)/globals.settings
#
unset force
if [[ "$1" == "--force" ]]; then
  force=1
  shift
fi
PACKAGE=$1
PIDSIG=$2
#
if [[ -f "$LOCKDIR/${PACKAGE}_start_progress" ]]; then
  if [[ -z "$PIDSIG" ]]; then
    PIDSIG=$(sed -n '$s/ .*//p' "$LOCKDIR/${PACKAGE}_start_progress")
  fi
  echo "$PIDSIG KILLSTART" >>"$LOCKDIR/${PACKAGE}_start_progress"
  read pidsig p pid prg < <(grep "^$PIDSIG PRGSTART " "$LOCKDIR/${PACKAGE}_start_progress" | tail -1)
  if [[ -n "$force" ]]; then
    echo -n "Der Start wird abgebrochen "
    Z=44
  else
    echo -n "Der Start wird spätestens in 45 Sekunden abgebrochen "
    Z=0
  fi
  while [[ $Z -lt 45 && "$p" != "PRGSTART" && -f "$LOCKDIR/${PACKAGE}_start_progress" ]]; do
    sleep 1
    Z=$(( $Z + 1 ))
    read pidsig p pid prg < <(grep "^$PIDSIG PRGSTART " "$LOCKDIR/${PACKAGE}_start_progress" | tail -1)
  done
  while [[ -f "$LOCKDIR/${PACKAGE}_start_progress" ]]; do
    sleep 1
    Z=$(( $Z + 1 ))
    if [[ $Z -gt 45 && $Z -lt 51 && "$p" = "PRGSTART" ]]; then
      if ps -ef | awk '$2 == '$pid'{print $0}' | grep -Fq "$prg "; then
        kill $pid
      fi
    fi
    echo -n "."
  done
  echo "
Start abgebrochen."
else
  echo "Der Start kann nicht abgebrochen werden."
fi
