#
# dcast: Create template dir for slave nodes.

require "libexec/nodes_class"
require 'fileutils'

def fstab(file, master_ip)
  select_dir = Array.new
  unselect_dir = ["/tftpboot", "/lost+found", "/proc", "/mnt", "/floppy", "/cdrom", "/media", "/etc", "/boot", "/dev", "/tmp", "/var", "/sys", "/home", "/root"]

  Dir.glob("/*").each{|lsdir|
    if FileTest.directory?(lsdir)
      select_dir.push(lsdir)
    end
  }
  select_dir = select_dir - unselect_dir

  open(file, "w"){|io|
    io.print <<EOF
# <file system> <mount point>   <type>  <options>               <dump>  <pass>
proc                   /proc    proc    soft,noac 0   2
/dev/fd0               /floppy  auto    defaults,user,noauto            0   0
EOF
   select_dir.each{|dir|
      io.puts "#{master_ip}:#{dir}      #{dir}     nfs     soft,noac 0   2"
    }
    io.puts "#{master_ip}:/home      /home     nfs     rsize=32768,wsize=32768,soft,noac 0   2"
    io.puts "#{master_ip}:/root      /home     nfs     rsize=32768,wsize=32768,soft,noac 0   2"
  }
end

def interfaces(file)
  open(file, "w"){|io|
    io.puts "#iface lo inet loopback"
    io.puts "auto lo"
    io.puts "iface lo inet loopback"
    io.fsync
  }
end

def exports(file)
  io = open(file, "w")
  io.print <<"EOF"
# /etc/exports: the access control list for filesystems which may be exported
#               to NFS clients.  See exports(5).
EOF
  io.close
end

def slave_hosts_config(diskless, ip, name, domain)
  IO.popen('echo "127.0.0.1        localhost" > /tmp/hosts')
  IO.popen('sed "s/^127\.0\.0\.1/#127\.0\.0\.1/g" /etc/hosts >> /tmp/hosts')
  IO.popen('sync')

  FileUtils.cp("/tmp/hosts", diskless + "/etc/hosts")

  io = File.open(diskless + "/etc/hosts", "a")
  io.puts ""
  io.puts "# dcast create"

  ip.size.times{|a|
    io.puts ip[a] + "\t" + name[a] + "\t" + name[a] + "." + domain
  }
  io.puts "# dcast end"
  io.close
end

def create_template(tftpboot)
  diskfull = tftpboot + "/diskfull"
  diskless = tftpboot + "/diskless"
  master = Nodes.new("master")

  # initialize
  FileUtils.rm_r(diskless) if FileTest.exist?(diskless)
  FileUtils.rm_r(diskfull) if FileTest.exist?(diskfull)
  FileUtils.mkdir_p(diskless + "/etc/network")
  FileUtils.mkdir_p(diskfull + "/etc/network")
  
  # create files
#  fstab(diskless + "/etc/fstab", master.ip)      # /etc/fstab
  #fstab
  diskless_fstab(diskless + "/etc/fstab",  Path.new.fstab_conf, master.ip)
  diskfull_fstab(diskfull + "/etc/fstab",  Path.new.fstab_conf, master.ip)
  FileUtils.mkdir_p(tftpboot + "/boot/")
  FileUtils.cp(diskfull + "/etc/fstab", tftpboot + "/boot/fstab")

  interfaces(diskless + "/etc/network/interfaces") # /etc/network/interfaces
  
  nodes = Nodes.new("all")
  slave_hosts_config(diskless, nodes.ip, nodes.name, nodes.domain) # /etc/hosts

  exports(diskless + "/etc/exports") # /etc/hosts

  FileUtils.mkdir_p(tftpboot + "/boot/root/")
  FileUtils.cp("/root/.rhosts", tftpboot + "/boot/root/.rhosts") # /root/.rhosts
end
