###
### removecluster.jacl 
###
###
###  Stop cluster
###  Remove cluster
###  
###  Usage:
###     
###  wsadmin.sh -username system \
###             -password \
###             -f removecluster.jacl clustername 
###
### 
###  Arguments:
###
###      arg1 - cluster name
###
###


proc removecluster {clusterName} {

  ###
  ### set up globals
  ###

  global AdminConfig
  global AdminControl
  global AdminApp

  set cluster [$AdminControl completeObjectName type=Cluster,name=$clusterName,*]
  puts "removecluster.jacl: Invoking stop for cluster $clusterName" 

  if {[llength $cluster] != 0} {
     $AdminControl invoke $cluster stop
  }



  puts "removecluster.jacl: removing the ServerCluster $clusterName"


  set clusterId [$AdminConfig getid /ServerCluster:$clusterName/]
  puts "clusterId: $clusterId"

  if {[llength $clusterId] == 0} {
     puts "$clusterName not found"
     exit
  }

  set xyz [$AdminConfig remove $clusterId]
  puts $xyz 

  $AdminConfig save




  ###
  ### Ask the ClusterMgr to refresh its list of clusters
  ###
  ###

  puts "Getting cluster manager..."
  set cellname [$AdminControl getCell]
  set clusterMgr [$AdminControl completeObjectName type=ClusterMgr,cell=$cellname,*]

  if {[llength $clusterMgr] == 0} {
      puts "clusterMgr MBean not found for cell $cellname"
      return
  }

  puts "Retrieving clusters..."
  $AdminControl invoke $clusterMgr retrieveClusters


  set cells [$AdminConfig list Cell]

  puts "Syncing nodes in $cells"
  foreach cell $cells {
       set cname [$AdminConfig showAttribute $cell name]
       set nodes [$AdminConfig list Node $cell]

       puts " "
       puts "Cell: $cname         "

       foreach node $nodes {

          set nname [$AdminConfig showAttribute $node name]
          puts " "
          puts "Syncing node: $nname            "


          puts "Checking for the existence of a NodeSync MBean on node $nname"
          set nodeSync [$AdminControl completeObjectName type=NodeSync,node=$nname,*]

          if {[llength $nodeSync] != 0} {
             puts "Syncing $nname $nodeSync..."
             $AdminControl invoke $nodeSync sync
             puts "Done with synchronization...."
       }
    }
  }
}
 


###
### Main
###

if { !($argc == 1) } {
   puts ""
   puts "removecluster.jacl "
   puts ""
   puts "Args include: "
   puts "   Cluster name "
   puts " "
   puts "For example:"
   puts "     "
   puts "  wsadmin -username system \ "
   puts "          -password password \ "
   puts "          -f removecluster.jacl clustername "
   puts " "
} else { 
   set clusterName      [lindex $argv 0]  

   removecluster $clusterName 
}