#!/bin/ksh

# attempts a few times to write to a file atomically via creating a
# temp file and a hardlink

usage() {
    echo "Usage: $0 [--overwrite] <file> <contents>" 1>&2
    exit 1
}

overwrite=
#breaklock=
while [ "$#" -gt 2 ] || [[ "$1" == --* ]] ; do
    case "$1" in
        --overwrite)
            overwrite=-f
            shift
            ;;
#        --breaklock)
#            breaklock=true
#            shift
#            ;;
        *)
            usage
            ;;
    esac
done

if [ "$#" -ne 2 ] ; then
    usage
fi

file="$1"
contents="$2"

tmp=`mktemp "$file.tmpwrite.XXXXXX"` || exit 1
chmod 644 $tmp
echo "$contents" > "$tmp"
i=0
while ! ln $overwrite "$tmp" "$file" 2>/dev/null ; do
    if [ "$i" -gt 65 ] ; then
        echo "Giving up on $file"
        rm "$tmp"
        exit 1
    fi
    if [ "$i" -eq 0 ] ; then
        echo -n "Retrying $file"
    else
        echo -n .
    fi
    sleep 1
    i=$((i+1))
done
if [ "$i" -ne 0 ] ; then
    echo
fi
rm "$tmp"
