# /にあるディレクトリを抽出
def root_dir()
  select_dir = Array.new
  Dir.glob("/*").each{|lsdir|
    if FileTest.directory?(lsdir)
      select_dir.push(lsdir)
    end
  }

  return select_dir
end

# fstab.confに書いてあるディレクトリを抽出
def fstab_conf_dir(conf)
  define_dir = Array.new
  open(conf, "r"){|io|
    while line = io.gets
      define_dir.push(line.split[1]) if line.split[1] != nil
    end
  }

  return define_dir
end

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

  select_dir = root_dir() # /にあるディレクトリを抽出

  if FileTest.exist?(conf)
    define_dir = fstab_conf_dir(conf) # fstab.confに書いてあるディレクトリを抽出

    # 有効なディレクトリのみ抽出
    select_dir = select_dir - unselect_dir - define_dir
 
    open(fstab, "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}\t#{dir}\tnfs\tsoft,noac 0   2"
      }
    }

    # fstab.conf内の定数を変換して書き込み($MASTER -> master_ip)
    open(fstab, "a"){|f|
      open(conf, "r"){|io|
        while line = io.gets
          f.print line.sub("$MASTER", master_ip) if line.split[1] != nil
        end
      }
    }

  else # もし、fstab.confがない場合
    select_dir = select_dir - unselect_dir

    open(fstab, "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}\t#{dir}\tnfs\tsoft,noac\t0 2"
      }
      io.puts "#{master_ip}:/home\t/home\tnfs\trsize=32768,wsize=32768,soft,noac 0   2"
      io.puts "#{master_ip}:/root\t/home\tnfs\trsize=32768,wsize=32768,soft,noac 0   2"
    }
  end
end

def diskfull_fstab(fstab, conf, master_ip)
  if FileTest.exist?(conf)
    # fstab.conf内の定数を変換して書き込み($MASTER -> master_ip)
    open(fstab, "w"){|f|
      open(conf, "r"){|io|
        while line = io.gets
          f.print line.sub("$MASTER", master_ip) if line.split[1] != nil
        end
      }
    }
  end
end
