
## PanTasks scripts for Phase 2

# tasks: p2pending p2update ppImage
#
# queues: 
#   p2pending: expID class classID url
#
# globals: 

queueinit stdout
queueinit stderr
queueinit p2pending

macro p2parse
  if ($0 != 7)
    echo "usage: p2parse (key) (expID) (class) (classID) (url) (state)"
    break
  end
  $expID   = $2
  $class   = $3
  $classID = $4
  $url     = $5
  $key     = $expID.$classID
end

# p2pending : search for images to be processed
task	       p2pending
  command      p2search.sh -pending
  host         local

  # timeout shorter than exec so jobs do not build up
  periods      -exec     5
  periods      -poll     1
  periods      -timeout  4

  # success
  task.exit    0
    local i Nstdout

    # pop off the header line
    queuepop stdout

    # keep only new, unique entries (URL is key)
    queuesize stdout -var Nstdout
    for i 0 $Nstdout
      queuepop stdout -var line
      p2parse unknown $line new
      queuepush p2pending -uniq -key 0 "$key $line new"
    end
    echo "loaded p2pending, current state:"
    queueprint p2pending
  end
end

# ppImage : submit an image for processing by ppImage
task	       ppImage
  periods      -exec 1
  periods      -timeout 120

  task.exec
    local Npending
    queuesize  p2pending -var Npending
    if ($Npending == 0) break

    # add in system status interruptions later
    # if ($network == 0) break
    
    queuepop p2pending -var line -key 5 new
    if ("$line" == "NULL") break
    p2parse $line

    echo "new ppImaage: $key $expID $class $classID $url run"
    queuepush p2pending "$key $expID $class $classID $url run"

    # need to decide real name for this function
    # $host = `chip.host $camera $chip`
    # host $host

    host local
    echo command ppImage.sh $key $url $classID
    command ppImage.sh $key $url $classID
  end

  # success
  task.exit    0
    # if ppImage updates the DB:
    echo "done with $taskarg:1"
    queueinit stdout
    queuepop p2pending -key 0 $taskarg:1 -var line
    echo "got line: $line"

    if ("$line" == "NULL") 
      echo "missing entry in p2pending queue?"
      break
    end

    p2parse $line
    queuepush p2pending "$key $expID $class $classID $url done"
    echo queuepush p2pending "$key $expID $class $classID $url done"
    
    # if ppImage does NOT update the DB:
  end

end

# p2update : search for images to be processed
task	       p2update
  command      p2search -update
  host         local

  # timeout shorter than exec so jobs do not build up
  periods      -exec     100
  periods      -poll     1
  periods      -timeout  4

  # task is never allowed to run
  task.exec
    break
  end
end

# p2done : search for images to be processed
task	       p2done
  command      p2search -done
  host         local

  # timeout shorter than exec so jobs do not build up
  periods      -exec     100
  periods      -poll     1
  periods      -timeout  4

  # task is never allowed to run
  task.exec
    break
  end
end
