#!/bin/bash

# CHECK UPTIME

RESUMED_TIMESTAMP_MICRO=$(journalctl -t systemd-sleep -b 0 -o json MESSAGE="System resumed." -n1 | jq -r .__REALTIME_TIMESTAMP)
if [[ -z "$RESUMED_TIMESTAMP_MICRO" ]]
then
  UPTIME=$(cat /proc/uptime | cut -d' ' -f1 | cut -d'.' -f1)
else
  RESUMED_TIMESTAMP=$(expr $RESUMED_TIMESTAMP_MICRO / 1000000)
  NOW_TIMESTAMP=$(date +%s)
  UPTIME=$(expr $NOW_TIMESTAMP - $RESUMED_TIMESTAMP)
fi


MIN_UPTIME=$(expr 60 \* 15)
if [[ "$UPTIME" -lt "$MIN_UPTIME" ]]
then
  echo "ABORT: uptime of ${UPTIME}s is lower than minimum of ${MIN_UPTIME}s"
  exit 75
fi

# CHECK FOR RUNNING TIMERS

for SERVICE in $(systemctl list-timers --no-pager --no-legend --state active -o json | jq -r '.[] | .activates')
do
  if [[ "$SERVICE" = "$THIS_SERVICE" ]]
  then
    continue
  elif systemctl is-active "$SERVICE" --quiet
  then
    echo "ABORT: service $SERVICE is running by timer"
    exit 75
  fi
done

# CHECK FOR INCOMING SSH CONNECTIONS

LOGINS=$(netstat -np | grep 'ESTABLISHED.*sshd' | tr -s ' ' | cut -d' ' -f5,7,8)
if ! [[ -z "$LOGINS" ]]
then
  echo "ABORT: incoming ssh connections: $LOGINS"
  exit 75
fi

# CHECK FOR OUTGOING SSH CONNECTIONS

LOGINS=$(netstat -np | grep 'ESTABLISHED.*ssh[^d]' | tr -s ' ' | cut -d' ' -f5,7,8)
if ! [[ -z "$LOGINS" ]]
then
  echo "ABORT: outgoing ssh connections: $LOGINS"
  exit 75
fi

# SUSPEND!

if [[ "$1" = check ]]
then
  echo "WOULD SESPEND"
  exit 0
else
  echo "SESPENDING AFTER TIMEOUT"

  for i in 1 2 3 4 5 6
  do
    echo "TIMEOUT ${i} success"
    sleep 10

    # check if condition is still met
    if "$0" check
    then
      continue
    else
      echo "SESPENSION ABORTED"
      exit 75
    fi
  done

  echo "SESPENDING"
  downtime
  systemctl suspend
  exit 0
fi
