#
# fileop.rb
#

module FileOperations

  def mkdir_p(dirname, prefix = nil)
    dirname = prefix + dirname if prefix
    $stderr.puts "mkdir -p #{dirname}" if verbose?
    return if no_harm?

    # does not check '/'... it's too abnormal case
    dirs = dirname.split(%r<(?=/)>)
    if /\A[a-z]:\z/i =~ dirs[0]
      disk = dirs.shift
      dirs[0] = disk + dirs[0]
    end
    dirs.each_index do |idx|
      path = dirs[0..idx].join('')
      Dir.mkdir path unless File.dir?(path)
    end
  end

  def rm_f(fname)
    $stderr.puts "rm -f #{fname}" if verbose?
    return if no_harm?

    if File.exist?(fname) or File.symlink?(fname)
      File.chmod 0777, fname
      File.unlink fname
    end
  end

  def rm_rf(dn)
    $stderr.puts "rm -rf #{dn}" if verbose?
    return if no_harm?

    Dir.chdir dn
    Dir.foreach('.') do |fn|
      next if fn == '.'
      next if fn == '..'
      if File.dir?(fn)
        verbose_off {
          rm_rf fn
        }
      else
        verbose_off {
          rm_f fn
        }
      end
    end
    Dir.chdir '..'
    Dir.rmdir dn
  end

  def move_file(src, dest)
    File.unlink dest if File.exist?(dest)
    begin
      File.rename src, dest
    rescue
      File.open(dest, 'wb') {|f| f.write File.read(src) }
      File.chmod File.stat(src).mode, dest
      File.unlink src
    end
  end

  def install(from, dest, mode, prefix = nil)
    $stderr.puts "install #{from} #{dest}" if verbose?
    return if no_harm?

    realdest = prefix + dest if prefix
    realdest += '/' + File.basename(from) if File.dir?(realdest)
    str = File.read(from)
    if diff?(str, realdest)
      verbose_off {
        rm_f realdest if File.exist?(realdest)
      }
      File.open(realdest, 'wb') {|f| f.write str }
      File.chmod mode, realdest

      File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| f.puts dest }
    end
  end

  def diff?(orig, targ)
    return true unless File.exist?(targ)
    orig != File.read(targ)
  end

  def command(str)
    $stderr.puts str if verbose?
    system str or raise RuntimeError, "'system #{str}' failed"
  end

  def ruby(str)
    command config('ruby-prog') + ' ' + str
  end
  
  def make(task = '')
    command config('make-prog') + ' ' + task
  end

  def extdir?(dir)
    File.exist?(dir + '/MANIFEST')
  end

  def all_files_in(dirname)
    Dir.open(dirname) {|d|
      return d.select {|ent| File.file?("#{dirname}/#{ent}") }
    }
  end

  REJECT_DIRS = %w(
    CVS SCCS RCS CVS.adm
  )

  def all_dirs_in(dirname)
    Dir.open(dirname) {|d|
      return d.select {|n| File.dir?("#{dirname}/#{n}") } - %w(. ..) - REJECT_DIRS
    }
  end

end


class File

  def File.dir?(path)
    # for corrupted windows stat()
    File.directory?((path[-1,1] == '/') ? path : path + '/')
  end

end
