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

require "libexec/path_class"
require "libexec/check"
require "libexec/nodes_class"
require "libexec/backup"
require "libexec/convert_config"
require "libexec/create_boot"
require "libexec/create_template"
require "libexec/create_slave"
require "libexec/service"
require "libexec/compression"
require "libexec/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
#############################
  parser.parse!

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

begin
  # 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, path.initrd, master.ip)
  create_slave_dir(slave.ip, path.tftpboot)
  if alldiskless
    diskless_flag(path.tftpboot, slave.name)
  end
  
  # Service restart
  Array service_cmds = [path.dhcp_cmd, path.pxe_cmd, path.nfs_cmd]
  puts ""
  service_restart(service_cmds)

  unless alldiskless
    compression(path.tftpboot + "/boot/")
  end

  # End
  puts "\nAll 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
