#!/usr/local/qddb/bin/qtclsh
#
# nextClient.qtcl - output next Clients relation ID and increment counter
#
set S [qddb_schema open /var/lib/ISPutil/qdDBs/Setup]
set K [qddb_search $S -prunebyattr ClientID r .*]
set T {}
foreach i [qddb_keylist get $K] {
    set T [qddb_tuple read $S $i]
    if {[llength $T] > 0} {
	break
    }
}
if {[string compare $T {}] == 0} {
    puts "You must set up fields in the Setup screen first"
    return
}
qddb_keylist delete $K
while {[qddb_tuple lock $T] == 0} {
    puts "Setup record locked, retrying..."
    exec sleep 1
}
set V [qddb_view define $T {
    {ClientID gv_tmpattr(clid)}
}]
puts -nonewline "Company.Contact.ID,1.1.1 "
set cid $gv_tmpattr(clid)
incr gv_tmpattr(clid)
qddb_tuple write $T
catch "qddb_tuple delete $T"
qddb_schema close $S
puts $cid
exit $cid
