1#!/bin/sh
2
3PATH=/bin:/usr/bin
4export PATH
5
6dir=$1.lock
7
8host=$HOSTNAME
9[ -z "$host" ] && host=$HOST
10[ -z "$host" ] && host=`hostname`
11
12user=$REMOTE_USER
13[ -z "$user" ] && user=$USER
14[ -z "$user" ] && user=$LOGNAME
15[ -z "$user" ] && user=`whoami`
16
17testfile=lock-test.$host.$2
18clean_up() {
19    rm -f "$testfile"
20}
21
22seconds=0
23while [ "$seconds" -lt 900 ]; do
24    if mkdir $dir >/dev/null 2>&1; then
25        [ "$seconds" = 0 ] || cat >&2 <<EOF
26
27Acquired `pwd`/$dir for PID $2 ($1)
28EOF
29        touch "$dir/for-$user@$host"
30        echo $1    > "$dir/command"
31        echo $host > "$dir/hostname"
32        echo $2    > "$dir/pid"
33        echo $user > "$dir/user"
34        clean_up
35        exit 0
36    fi
37    if [ "$seconds" = 0 ]; then
38        if [ x`echo -n` = x-n ]; then
39            n=''; c='\c'
40        else
41            n='-n'; c=''
42        fi
43        trap 'clean_up; exit 1' 1 2 15
44        if (echo >$testfile) 2>/dev/null  &&  test -s $testfile; then
45            echo $n "Waiting for `pwd`/$dir$c" >&2
46        else
47            if test -w .; then
48                problem="free space"
49            else
50                problem="permissions"
51            fi
52            echo "Unable to create a lock in `pwd`; please check $problem." >&2
53            clean_up
54            exit 1
55        fi
56    elif [ -f "$dir/for-$user@$host" -a -s "$dir/pid" ]; then
57        read old_pid < $dir/pid
58        if kill -0 "$old_pid" >/dev/null 2>&1; then
59            : # Keep waiting; evidently still alive
60        else
61            # Stale
62cat >&2 <<EOF
63
64Clearing stale lock `pwd`/$dir from PID $old_pid for PID $2 ($1)
65EOF
66            rm -rf "$dir"
67            continue
68        fi
69    elif [ ! -f "$dir/command" -o ! -f "$dir/hostname" -o ! -f "$dir/pid" \
70           -o ! -f "$dir/user" ]; then
71        # Incomplete; wipe out if preexisting and at least a minute old.
72        # Solaris's /bin/sh doesn't support test's -nt or -ot operators,
73        # hence the use of ls and head.
74        if [ $seconds = 60 ] \
75           &&  [ `ls -dt $dir $testfile | head -n1` = $testfile ]; then
76cat >&2 <<EOF
77
78Clearing old incomplete lock `pwd`/$dir for PID $2 ($1)
79EOF
80            rm -rf "$dir"
81            continue
82        fi
83    fi
84    sleep 5
85    echo $n ".$c" >&2
86    seconds=`expr $seconds + 5`
87done
88
89clean_up
90
91if test -f "$dir"; then
92    # old-style lock
93    echo
94    cat "$dir"
95else
96    fmt -74 <<EOF
97
98`cat $dir/user` appears to be running `cat $dir/command` in `pwd` as
99process `cat $dir/pid` on `cat $dir/hostname`.  If you have received
100this message in error, remove `pwd`/$dir and try again.
101EOF
102fi
103
104exit 1
105