require File.dirname(__FILE__) + '/../spec_helper.rb'

describe Account do
  before(:each) do
    @account = Account.create(
      :server => Server.create(:host => TEST_SERVER),
      :user => User.create(:name => TEST_USER)
    )

    @server = @account.server
    @user = @account.user
  end
  
  after(:each) do 
    @server.execute_command("sudo /usr/sbin/userdel --remove #{TEST_USER}")
  end
  
  describe "with a user" do  
    it "should create a user on a server" do
      @account.add_user
      @server.execute_command("id #{@user.name}")
      @server.output.should_not == ''
    end
  
    it "should ensure that user's home directory has the correct permissions" do
      @account.add_user
      @server.execute_command("sudo ls -la /home | grep #{@user.name}")
      @server.output.should =~ /^drwxr-xr-x/
    end
  end
  
  describe "with a user in a group" do
    before(:each) do
      @account.add_user
      @user.groups.new(:name => TEST_GROUP)
      @server.execute_command("sudo /usr/sbin/groupadd #{TEST_GROUP}")
    end
    
    after(:each) do
      @server.execute_command("sudo /usr/sbin/groupdel #{TEST_GROUP}")
    end

    it "should add the user to that group" do
      @account.add_to_groups

      @server.execute_command("groups #{@user.name}")
      @server.output.should =~ / ?#{TEST_GROUP} ?/
    end
  end
  
  describe "with a user with an ssh key" do
    before(:each) do
      @account.add_user
      @account.add_ssh_directory    
      @key_text = 'this is a key'
      @user.keys.create(:public_key => @key_text)
    end
    
    describe "on a server" do
      before(:each) do
        @account.write_ssh_key
      end

      it "should have the correct permissions" do
        @server.execute_command("sudo ls -la /home/#{@user.name}/.ssh/authorized_keys")
        @server.output.should =~ /^-rw-------/        
      end
    end
    
    describe "to be added" do
      it "should add that key" do
        @account.write_ssh_key
        @server.execute_command("sudo cat /home/#{@user.name}/.ssh/authorized_keys")
        @server.output.strip.should == @key_text
      end
    end

    describe "to be updated" do
      before(:each) do
        @account.write_ssh_key
        @updated_key = 'this is also a key'
        @user.keys.first.public_key = @updated_key
      end

      it "should update that key" do
        @account.write_ssh_key
        @server.execute_command("sudo cat /home/#{@user.name}/.ssh/authorized_keys")
        @server.output.strip.should == @updated_key
      end
    end
  end
end