@TCL_STARTUP@

# Agent Tcl
# Bob Gray
# 29 October 1995
#
# disk.tcl
#
# This agent illustrates how to write a migrating agent to disk and then
# send it to the server at a later time.

proc indirect_jump {} {

  global agent

    # Save the current state of the agent to a file.  This state image is
    # sent to the server at a later time using agent_transfer.  When the 
    # state image is restored and the new agent begins executing, agent_disk
    # returns the string "JUMPED" in the new agent.

  set filename [pwd]/agent.image
  set fd [open $filename w]
  set state [agent_disk $fd]

  if {$state == "JUMPED"} {

      # I'm in the new agent.

    return HELLO

  } else {

      # I'm in the agent that called agent_disk.

    close $fd
    return $filename 
  }
}

  # Since the agent_disk is being performed in a child agent, we must turn
  # on signatures so that the server can authenticate the agent's owner;
  # also the server must be configured so that this owner has authority to
  # write to the disk.  We are working to extend the security policy so
  # that any agent can open one specific file for doing agent_disk commands;
  # such an extension is actually straightforward if you want to try it
  # yourself although it does require a detailed understanding of the D'Agents
  # system.

set code [
    catch {
       security signatures on
    } result
]

if {$code} {
    puts "Unable to turn on digital signatures:"
    puts ""
    puts $result
    puts ""
    puts "Proceeding anyways ..."
    puts ""
}

  # register the agent

agent_begin

  # submit the indirect_jump procedure 

agent_submit $agent(local-ip) -procs indirect_jump -script indirect_jump

  # wait for indirect_jump to send the filename

agent_receive code filename -blocking

if {$code != 0} {
  return -code error "indirect jump failed ($filename)"
}

  # display the filename

puts "The \"jump\" image has been stored in file $filename."

  # transfer the jump image to the server

puts "The \"jump\" image is being transferred to the server."
set fd [open $filename r]
agent_transfer $agent(local-ip) $fd
close $fd

  # wait for indirect_jump to send the HELLO

agent_receive code string -blocking

if {$code != 0} {
  return -code error "agent failed ($string)"
}

puts "The \"jumped\" agent says $string."

  # done

agent_end
