#!/usr/bin/env ruby
#
# dcast $Revision: 0.01 $
#
# Copyright (C) 2006, Masahiro Nakao <mnakao@pre-dawn.net>
# You can redistribute it and/or modify it under GPL2 or more.

require "path_class"
require "check"
require "nodes_class"
require "backup"
require "convert_config"
require "create_boot"
require "create_template"
require "create_slave"
require "service"
require "compression"
require "convert_fstab"
require 'optparse'

# Create Path class
path = Path.new

# Check root user or not
check_uid()

#############################
# ץβ
#############################
alldiskless = false
parser = OptionParser.new
parser.banner = "Usage: #{File.basename($0)} [--alldiskless]"

parser.on("--alldiskless", "All node is composed as disless node."){|ar|
  puts "set: --alldiskless"
  alldiskless = true
}

#############################
# main
#############################
begin
  parser.parse!

  # Check exist "backup" and "tftpboot"
  check_dir_exist(path.backup)
  check_dir_exist(path.tftpboot)

  # Check configration files exist or not
  Array files=[path.dhcp, path.dhcp_i, path.pxe, path.pxe_kernel, path.kernel, path.mpich]
  files.push("/etc/hosts")
  files.push("/etc/hosts.equiv")
  files.push("/etc/exports")
  system("touch /root/.rhosts")
  files.push("/root/.rhosts")
  check_file_exist(files)
  
  # Backup curent configration files
  files = files - [path.pxe_kernel, path.kernel]
  setting_files_backup(path.backup, files)
  
  # Config master node
  slave = Nodes.new("slave")
  master = Nodes.new("master")
  all = Nodes.new("all")
  
  hosts_config(all.ip, all.name, all.domain)
  pxe_config(master.eth, master.ip)
  nfs_config(master.nwork, master.nmask)
  rsh_config(all.name)
  rhosts_config(all.name)
  mpich_config(path.mpich, all.name)
  dhcpd_config(path.dhcp, path.dhcp_i, path.tftpboot, master.eth, master.ip, master.nwork, master.nmask, master.bcast, slave.name, slave.ip, slave.mac)
  
  # Create slave dir
  create_template(path.tftpboot)
  mkdir_tftpboot(path.tftpboot, path.kernel, master.ip)
  create_slave_dir(slave.ip, path.tftpboot)
  unless alldiskless
    compression(path.tftpboot + "/boot/")
  else
    diskless_flag(path.tftpboot, slave.name)
  end
  
  # Service restart
  Array service_cmds = [path.dhcp_cmd, path.nfs_cmd, path.pxe_cmd]
  puts ""
  service_restart(service_cmds)
  
  # End
  puts "All Done."
  exit 0

rescue OptionParser::ParseError => err
  $stderr.puts err.message
#  $stderr.puts parser.help
  exit 1
rescue SignalException
  puts ""
  puts "DCAST¹ξ֤ᤷޤ"
  system("ruby dcast-allremove")
  exit 1
end
