@echo off

goto loop

rem --------------------------------

if exist "foo" (
	echo yesa
) else if exist "bar" (
	echo yesb
)

goto end


:lock_loop
mkdir lock
if '%errorlevel%' == '1' (
	ping 127.0.0.1 -w 10 -n 2 > nul
	goto lock_loop
)
rem acquire lock


goto end

rem --------------------------------

:loop

set tempname=tmp_%random%-%random%_%date: =-%T%time: =0%.tmp

rem set tempname=tmp_%time:~0,7%.tmp
rem debug -deliberate collisions

set tempname=%tempname::=-%
set tempname=%tempname:,=-%
set tempname=%temp%\%tempname%

if exist "%tempname%" (
	goto loop
) else (
	:lock_loop
	mkdir "%tempname%.prep"
	if ERRORLEVEL 1 ( rem this could easily deadlock if the other instance of the script failed and never released the lock (could add e.g. timeout and fail, or go straight to generating another name)
		rem echo "wait for lock"
		rem debug

		ping 127.0.0.1 -w 10 -n 2 > nul
		goto lock_loop
	) else (
		rem acquire lock

		if exist "%tempname%" (
			rem echo "came too late"
			rem debug

			rmdir "%tempname%.prep"
			goto loop
		)
		rem the lock is not there anymore but the temp file already exists
		rem release the lock and try again

		rem echo "oh yes"
		rem ping 127.0.0.1 -w 1000 -n 3 > nul
		rem debug

		rem now we are locked and the file does not exist

		type nul > "%tempname%"
		rem make the temp file

		rmdir "%tempname%.prep"
	)
)

echo %tempname%

:end
