#
# dcast: Create slave dir for network mount in /tftpboot.

require "fileutils"
require "hardlink"

def setting_slave(dir, tftpboot)
  hostname = tftpboot + dir + "/etc/hostname"
  resolv = tftpboot + dir + "/etc/resolv.conf"
  hosts = tftpboot + dir + "/etc/hosts"
  interfaces = tftpboot + dir + "/etc/network/interfaces"
  fstab = tftpboot + dir + "/etc/fstab"
  exports = tftpboot + dir + "/etc/exports"
  mtab = tftpboot + dir + "/etc/mtab"

  # /etc/hostname
  File.unlink(hostname) if File.exist?(hostname)

 # /etc/resolv.conf
  File.unlink(resolv) if File.exist?(resolv)
  
  # /etc/hosts
  File.unlink(hosts) if File.exist?(hosts)
  FileUtils.cp(tftpboot + "/diskless/etc/hosts", hosts)

  # /etc/network/interfaces
  File.unlink(interfaces) if File.exist?(interfaces)
  FileUtils.cp(tftpboot + "/diskless/etc/network/interfaces", interfaces)

  # /etc/fstab
  File.unlink(fstab) if File.exist?(fstab)
  FileUtils.cp(tftpboot + "/diskless/etc/fstab", fstab)

  # /etc/exports
  File.unlink(exports) if File.exist?(exports)
  FileUtils.cp(tftpboot + "/diskless/etc/exports", exports)

  # /etc/mtab
  File.unlink(mtab) if File.exist?(mtab)
  system("ln -sf /proc/mounts #{mtab}")
end

def create_slave_dir(ip, tftpboot)
  tftpboot = tftpboot + "/"
  ip.each{|dir|
    print "Creating " + dir + " dir..."
    FileUtils.mkdir_p(tftpboot + dir)
    FileUtils.cp_r(tftpboot + "/boot/etc", tftpboot + dir + "/etc")
    print "."
#    Dir.glob("/var/*").each{|lsdir|
#      if lsdir == "/var/lib"
#        hard_link(lsdir, tftpboot + dir)
#      else
#        Find.find(lsdir){|path|
#          FileUtils.mkdir_p(tftpboot + dir + path) if FileTest.directory?(path)
#        }
#     end
#    }
#    print "."

    setting_slave(dir, tftpboot)
#    FileUtils.mkdir(tftpboot + dir + "/tmp")
#    system("chmod 1777 #{tftpboot + dir + "/tmp"}")
    puts "Done."
  }
end

def diskless_flag(path, names)
  names.each{|name|
    open(path + "/slave/" + name, "w"){|io|
      io.puts "0"
    }
  }
end
