module m_uuid
implicit none

    integer, parameter::UUID_LENGTH = 36
    
    character(len=*), parameter::UUID_GENERATOR = "uuidgen"
    
contains

    function generate_uuid4() result(uuid)
    use utilities
    implicit none
    
        character(len=:), pointer::tempfile
        character(len=UUID_LENGTH)::uuid
        
        character(len=5)::fmt
        
        integer::unum
        
        tempfile => generate_temporary_filename()

        call execute_command_line(UUID_GENERATOR//" > "//trim(tempfile), wait=.true.)
        
        open(newunit=unum, action="read", file=tempfile, status="old")
        write(fmt, '(I3)') UUID_LENGTH
        fmt = "(A"//trim(adjustl(fmt))//")"
        read(unum, fmt) uuid
        close(unum)
        call unlink(tempfile)
        
        deallocate(tempfile)
    
    end function generate_uuid4

end module m_uuid