#!/bin/bash
#resurrect rtorrent when it dies and restart every 6 hours
hour=`date | grep -Po "\d\d:\d\d:\d\d" | grep -Po "^\d\d:\d\d"`

if [ "$hour" = "00:00" ] || [ "$hour" = "06:00" ] || [ "$hour" = "12:00" ] || [ "$hour" = "18:00" ];then
  killall -w -s 2 /usr/bin/rtorrent
  systemctl restart openvpn-client@windscribe-denmark.service
fi

currentip=`ps aux | grep rtorrent | grep -v "SCREEN" | grep -Po "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"`
tunip=`ip addr show tun0 | grep -Po "inet \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" | grep -Po "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"`

if [ "$currentip" = "$tunip" ];then
  echo "rtorrent is up"
else
  echo "restarting rtorrent"
  killall -w -s 2 /usr/bin/rtorrent
  rm -f /mnt/video/rtorrent/.session/rtorrent.lock
  sleep 5;/usr/bin/screen -dmfa -S rtorrent /usr/bin/rtorrent -b $tunip
fi