#!/bin/ksh

# attempts to read and clear an file atomically if it exists
# (or just read without clearing if --norm)

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

no_rm=
#lock=
#unlock=
while [ "$#" -gt 1 ] || [[ "$1" == --* ]] ; do
    case "$1" in
        --no-rm)
            no_rm=true
            shift
            ;;
#        --lock)
#            lock=true
#            shift
#            ;;
#        --unlock)
#            unlock=true
#            shift
#            ;;
        *)
            usage
            ;;
    esac
done

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

file="$1"
contents=
exit=1

tmp=`mktemp "$file.tmpread.XXXXXX"`  || exit 2 # error
if ! ln -f "$file" "$tmp" 2>/dev/null ; then # does not exist, don't
                                             # care about error text
                                             # if source not exist -
                                             # just return error code
    rm "$tmp"
    exit 1
fi
sed 's/ *#.*//' "$tmp"
if [ "$no_rm" ] ; then
    rm "$tmp"
else
    rm "$file" "$tmp"
fi
