###
### remove.jacl 
###
###  Stop a server on a given node 
###  Uninstall the given application,
###  Remove the server from the configuration.
###
###  This is a bi-modal script: it can be included in the wsadmin 
###  command invocation like this:
###  
###     wsadmin -f remove.jacl serverX nodeY myapp
###
###  or the script can be sourced from the wsadmin command line if:
###
###     wsadmin> source remove.jacl
###     wsadmin> remove serverX nodeY myapp
### 
###  The script expects some parameters:
### 
###      arg1 - server name
###      arg2 - node name
###      arg3 - application name
###
###

proc remove {serverName nodeName args} {


   ###
   ### check for optional argument 
   ###

   set app [lindex $args 0]

   if {[llength $args] > 1} {
      set appName [lindex $args 1]
   } else {
      set appName ""
   }

   ###
   ### set up globals
   ###
   global AdminConfig
   global AdminControl
   global AdminApp


   ###
   ###  Do we have a node by this name? 
   ###

   set node [$AdminConfig getid /Node:$nodeName/]

   puts "Checking for existence of node $nodeName..."

   if {[llength $node] == 0} {
      puts "remove: Error -- node not found for name $nodeName"
      return 
   }


   ###
   ###   Is a server by this name already running on the node? 
   ###

   puts "Checking to see if server $serverName is running on node $nodeName..."

   set runningServer [$AdminControl completeObjectName type=Server,node=$nodeName,process=$serverName,*]

   if {[llength $runningServer] < 0} {
      puts "remove: Error -- Server $serverName not running on node $nodeName"
      return 
   }



   ###
   ### Stop the server 
   ###

   puts "Stopping server $serverName ..."
   $AdminControl stopServer $serverName $nodeName
   puts "Done."


   ###
   ### Uninstall the application 
   ###
   puts "Uninstalling the application"
   $AdminApp uninstall $app


   ###
   ### Find the configuration object 
   ###

   set server [$AdminConfig getid /Node:$nodeName/Server:$serverName/]


   ###
   ### Remove it 
   ###

   $AdminConfig remove $server 



   ###
   ### Save all the changes 
   ###

   puts "Saving the configuration"
   $AdminConfig save
}


###
### Main
###
if { !($argc == 3) } {
   puts "Usage: remove.jacl server_name node_name, and application_name"
} else { 
   set serverName       [lindex $argv 0]  
   set nodeName         [lindex $argv 1]  
   set appName          [lindex $argv 2]

   remove $serverName $nodeName $appName
}