# Inspec test for recipe irrigate-php::deploy_qa_user

# The Inspec reference, with examples and extensive documentation, can be
# found at http://inspec.io/docs/reference/resources/

control 'deploy_qa_user' do
  # For using node attributes in tests
  nodes_dir = '/tmp/kitchen/nodes'
  output = command("ls #{nodes_dir}").stdout.strip
  node_json = "#{nodes_dir}/#{output}"

  if file(node_json).exist?
    node = json(node_json).params

    describe user node['default']['php']['deploy_user'] do
      it { should exist }
      its('uid') { should eq 1001 }
      its('home') { should eq node['default']['php']['deploy_home_dir'] }
      its('shell') { should eq '/bin/bash' }
    end

    describe group 'webdev' do
      it { should exist }
      its('gid') { should eq 1099 }
    end

    node['normal']['php']['deploy_group_members'].each do |user_name|
      describe user user_name do
        its('groups') { should include 'webdev' }
      end
    end

    user_home = node['default']['php']['deploy_home_dir']
    describe file "#{user_home}/.ssh/authorized_keys" do
      it { should exist }
      its('content') { should include node['default']['php']['qa_deploy_user_pub_key'] }
    end

    github_ssh_key_location = "#{node['default']['php']['deploy_home_dir']}/.ssh/id_rsa"
    describe file github_ssh_key_location do
      its('owner') { should eq node['default']['php']['deploy_user'] }
      its('mode') { should cmp '0400' }
    end

    describe file "#{node['default']['php']['deploy_home_dir']}/.ssh/config" do
      it { should exist }
      its('owner') { should eq node['default']['php']['deploy_user'] }
      its('group') { should eq node['default']['php']['deploy_user'] }
      its('mode') { should cmp '0600' }
      its('content') { should match(/Host \*(\n\t)StrictHostKeyChecking no\n/) }
    end

    cookbook_file = File.read("files/default/#{node['default']['php']['qa_deploy_user_github_pub_key']}")
    describe file "#{node['default']['php']['deploy_home_dir']}/.ssh/id_rsa.pub" do
      its('mode') { should cmp '0644' }
      its('content') { should eq cookbook_file }
    end

  else
    puts "File #{node_json} does not exist, skiping attribute-depending checks"
  end
end
