#
# dcast: Create template dir for slave nodes.

require '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 hosts(file, ip, name)
  io = open(file, "w")
  ip.each_with_index{|a, i|
    io.puts ip[i] + "\t" + name[i] + "\t" + name[i].split(/\./)[0]
  }
  io.puts ""

  io.print <<"EOF"
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
EOF
  io.fsync
  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")
  hosts(diskless + "/etc/hosts", nodes.ip, nodes.name) # /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
