#! /bin/sh

# Question 7:

# Modify your answer to question 5 so that if the program receives any
# of the following signals: INT, TERM, HUP or QUIT, the program will do
# all of the following:

# o print a message;
# o remove the lockfile;
# o exit with a non-zero exit status.

prog=$(basename $0)
uid_num=$(id -u)

lockfile="/tmp/${prog}.lock"
[ "$uid_num" -eq 0 ] && lockfile=/var/lock/subsys/${prog}.lock

signal_handler() {
    echo "received a signal; terminating"
    rm -f $lockfile
    exit 1
}


if [ -e "$lockfile" ]
then
    echo "lockfile exists"
    exit 1
else
    trap signal_handler INT TERM HUP QUIT
    touch $lockfile
    [ -e $lockfile ] || { echo "$prog: cannot create $lockfile"; exit 1; }
fi

# just to help in testing:
sleep 60
rm -f $lockfile