#!/bin/bash
#
# This script was made for random disconnects due to troublesome UPS units
#   running on USB interface using NUT software.
# The example in this script is made for BlueWalker PW VI 2200 LCD.
# But it might work with a lot of UPS with usbhid-ups driver.
#
#
# This configuration is based on the configuration of NUT,
#   ex. MONITOR: pwvi@192.168.0.1
#
# When the script is tested and ready to be used, it must be installed as
# a cronjob with a propriate user with access to restart NUT.
# You want to check the status of the UPS often as possible, here every minute:
#
# */1 * * * * /path/to/ups_autors.sh &> /dev/null
#

# UPS name
UPS=pwvi
# UPS address (ex: 127.0.0.1, localhost, 192.168.0.1...)
UPSADDR=192.168.0.1
# Path to upsdrvctl
UPSBINPATH=/sbin

# Start script
#-------------------------------------------
# Get status
UPSSTATUS="$(upsc $UPS@$UPSADDR ups.status 2>&1 | grep -v '^Init SSL')"

# Debug
#echo $UPSSTATUS

# Define what to look for (regexp), here: Error*
UPSERROR="^(Error*)"

# If Error message is triggered, stop and start UPS driver, else do nothing at all.
if [[ $UPSSTATUS =~ $UPSERROR ]]; then
	echo "Stopping driver for $UPS (ignore error messages):"
	$UPSBINPATH/upsdrvctl stop $UPS
	echo "Starting driver for $UPS:"
	$UPSBINPATH/upsdrvctl start $UPS
fi