#!/bin/bash
# Allo-GG
# Routine de verification de l'etat des services

echo "********************"
date
echo "********************"
echo

# BLINK for 10 sec
timeout 10 /usr/local/bin/gpio -g blink 18 &

# HORLOGE
if timedatectl status | grep -q 'Time zone: Europe/Paris (CEST, +0200)'
then
  if timedatectl status | grep -q 'Network time on: yes'
  then
    if timedatectl status | grep -q 'NTP synchronized: yes'
    then
      if timedatectl status | grep -q 'RTC in local TZ: no'
      then
        echo "[✅ OK] Horloge"
      else
        echo "[❌ ERREUR] Horloge - RTC in local TZ"
        /usr/local/bin/gpio -g write 18 1
        exit
      fi
    else
      echo "[❌ ERREUR] Horloge - NTP not synchronized"
      /usr/local/bin/gpio -g write 18 1
      exit
    fi
  else
    echo "[❌ ERREUR] Horloge - Network time is OFF"
    /usr/local/bin/gpio -g write 18 1
    exit
  fi
else
  echo "[❌ ERREUR] Horloge - Bad Timezone"
  /usr/local/bin/gpio -g write 18 1
  exit
fi

# LOG2RAM
if mount | grep -q 'log2ram on /var/log type tmpfs'
then
  echo "[✅ OK] Log2Ram"
else
  echo "[❌ ERREUR] Log2Ram"
  /usr/local/bin/gpio -g write 18 1
  exit
fi

# APACHE
if /usr/sbin/service apache2 status | grep -q 'running'
then
  echo "[✅ OK] Apache"
else
  echo "[❌ ERREUR] Apache"
  /usr/local/bin/gpio -g write 18 1
  exit
fi

# CRON
if /usr/sbin/service cron status | grep -q 'running'
then
  echo "[✅ OK] CRON"
else
  echo "[❌ ERREUR] CRON"
  /usr/local/bin/gpio -g write 18 1
  exit
fi

# SSH
if /usr/sbin/service ssh status | grep -q 'running'
then
  echo "[✅ OK] SSH"
else
  echo "[❌ ERREUR] SSH"
  /usr/local/bin/gpio -g write 18 1
  exit
fi

# WIRINGPI
if /usr/local/bin/gpio -v | head -n 1 | grep -q 'gpio version: [0-9]'
then
  echo "[✅ OK] WiringPi"
else
  echo "[❌ ERREUR] WiringPi"
  /usr/local/bin/gpio -g write 18 1
  exit
fi

# INTERNET

# tester 5 ping
if ping -c5 1.1.1.1 | grep -q '0% packet loss'
# Si la reponse est 0 paquets perdu, alors OK
then
  echo "[✅ OK] Internet"
# Mais sinon, il y a un probleme
else
  # Tentative de relancer le wifi ...
  sleep 2
  echo
  echo "[❌ ERREUR] Probleme sur le Wifi ? Tentative de relancer la connexion en cours ..."
  ifdown --force wlan0
  sleep 2
  ifup wlan0
  sleep 2

  # ... puis refaire un test, en testant 10 ping cette fois
  if ping -c10 1.1.1.1 | grep -q '0% packet loss'
  # Si la reponse est 0 paquets perdu, alors finalement tout va bien
  then
  echo "[✅ OK] Internet"
  # Mais si le probleme est toujours present, alors on alerte :
  else
  echo "[❌ ERREUR] Internet"
  /usr/local/bin/gpio -g write 18 1
  exit
  fi
fi

# Tout va bien ^_^ Allumage de la LED d'etat.
/usr/local/bin/gpio -g write 18 0
echo
echo "[✅ OK] Tout va bien 👌"
echo "********************"
echo
exit
