#!/mod/bin/jimsh

set ::lock::locks {}

proc acquire_lock {id {timeout 0} {interval 0.2}} {
	try {
		if {[dict exists $::lock::locks $id]} {
			#error "Lock already held"
			set lock $::lock::locks($id)
		} else {
			set file "/var/lock/.webiflock_[system filename $id]"
			set fh [open $file w]
			set lock [list file $file fh $fh]
			set ::lock::locks($id) $lock
		}

		incr timeout [clock seconds]

		while {[$lock(fh) lock] != 1} {
			if {[clock seconds] > $timeout} { return 0 }
			sleep $interval
		}

		return 1
	} on error {msg opts} {
		incr opts(-level)
		return {*}$opts $msg
	}
}

proc release_lock {id} {
	try {
		if {![dict exists $::lock::locks $id]} {
			error "Lock not held."
		}
		set lock $::lock::locks($id)

		set ret [$lock(fh) unlock]
		$lock(fh) close
		dict unset ::lock::locks $id
		return $ret
	} on error {msg opts} {
		incr opts(-level)
		return {*}$opts $msg
	}
}

