#!/bin/bash
#
# File: wait4power
# Auth: Peter strand
# Desc: waits for utility power before going multiuser
# Date: 29 July 2000
#
echo "Checking for utility power..."

DRIVERPATH=/usr/local/ups/bin
export PATH=$PATH:$DRIVERPATH

# Get config
if [ -f /etc/sysconfig/ups ]; then 
    . /etc/sysconfig/ups 
else 
    exit 1 
fi   

# Prepare ramdisk
dd if=/dev/zero of=/dev/ram1 bs=1k count=64 &> /dev/null
mke2fs -m0 /dev/ram1 &> /dev/null
mount /dev/ram1 /var/state/ups
chown -R nobody.nobody /var/state/ups

# If the UPS is locally attached, start driver and upsd
if [ "$HOST" = "localhost" ]; then                                      
    if [ -f $DRIVERPATH/$MODEL -a -x $DRIVERPATH/$MODEL ]; then         
	$MODEL $OPTIONS $DEVICE                      
    else                                                                
	echo "$DRIVERPATH/$MODEL - no driver"                        
	exit 255                                                        
    fi                                                                  
    upsd                                                         
fi

# Check status
CMD="/usr/local/ups/bin/upsc localhost | grep 'STATUS\:.*OB.*'"
eval $CMD > /dev/null
RESULT=$?

if [ $RESULT -eq 0 ]; then
    echo "The system is running on battery power!"
    echo "The boot process will continue when utility power returns."
    echo "This is a safe state. You may cut power at any time."
    echo
fi

while [ $RESULT -eq 0 ]; do
    NOW=`date`
    echo -ne "\r${NOW}: Running on battery power, waiting"
    sleep 5
    eval $CMD > /dev/null
    RESULT=$?
done

echo -e "\nPower OK, continuing"

# Clean up
kill `pidof upsd`
kill `pidof $MODEL`
umount /var/state/ups


