require File.dirname(__FILE__) + '/test_helper'

class UtilTest < Test::Unit::TestCase
  def setup
    @path = "/tmp/astrovan.#{Time.now.to_i}"
    super
  end

  def teardown
    system "rm -rf #{@path} #{@path}.lnk"
    super
  end

  def test_should_mkdir
    assert !File.exist?(@path)
    using 'astrovan.local', :password => ENV['PASSWORD'], :path => @path do
      mkdir path
    end
    assert File.exist?(@path)
    assert File.directory?(@path)
  end

  def test_should_rm_file
    create_file
    using 'astrovan.local', :password => ENV['PASSWORD'], :path => @path do
      rm path
    end
    assert !File.exist?(@path)
  end

  def test_should_not_rm_directory
    system "mkdir -p #{@path}"
    assert File.exist?(@path)
    assert File.directory?(@path)
    assert_raise(RuntimeError) do
      using 'astrovan.local', :password => ENV['PASSWORD'], :path => @path do
        rm path
      end
    end
    assert File.exist?(@path)
    assert File.directory?(@path)
  end

  def test_should_rm_directory_with_recursive_option
    system "mkdir -p #{@path}"
    assert File.exist?(@path)
    assert File.directory?(@path)
    using 'astrovan.local', :password => ENV['PASSWORD'], :path => @path do
      rm path, :recursive => true
    end
    assert !File.exist?(@path)
  end

  def test_should_symlink
    data = create_file
    target = @path + ".lnk"
    using 'astrovan.local', :password => ENV['PASSWORD'], :path => @path, :target => target do
      symlink path, :to => target
    end
    assert File.exist?(target)
    assert File.symlink?(target)
    assert_equal data, File.open(target) { |f| f.gets.chomp }
  end

  def test_should_symlink_to_directory
    system "mkdir -p #{@path}"
    data = create_file("#{@path}/hello")
    target = @path + ".lnk"
    assert File.exist?(@path)
    assert File.directory?(@path)
    using 'astrovan.local', :password => ENV['PASSWORD'], :path => @path, :target => target do
      symlink path, :to => target
    end
    assert File.exist?(target)
    assert File.symlink?(target)
    assert_equal data, File.open("#{target}/hello") { |f| f.gets.chomp }
  end

  def test_should_replace_symlink_to_directory
    system "mkdir -p #{@path}"
    data = create_file("#{@path}/hello")
    target = @path + ".lnk"
    assert File.exist?(@path)
    assert File.directory?(@path)
    system "ln -s /var/tmp #{target}"
    using 'astrovan.local', :password => ENV['PASSWORD'], :path => @path, :target => target do
      symlink path, :to => target
    end
    assert File.exist?(target)
    assert File.symlink?(target)
    assert_equal data, File.open("#{target}/hello") { |f| f.gets.chomp }
  end

protected
  def create_file(path = nil)
    path ||= @path
    data = Time.now.utc.to_s
    File.open(path,'w') { |f| f.puts data }
    assert File.exist?(path)
    assert !File.directory?(path)
    data
  end
end