control 'stmtdb_users_ssh' do
  attribute_file = '/tmp/kitchen/node_attributes.json'
  if file(attribute_file).exist?
    node = json(attribute_file).params

    if node['stmtdb']['ssh_users'] && !node['stmtdb']['ssh_users'].empty?
      node['stmtdb']['ssh_users'].each do |user_attr|
        describe user user_attr['username'] do
          it { should exist }
          its('uid') { should eq user_attr['uid'] }
          its('home') { should eq user_attr['home'] }
          its('shell') { should eq user_attr['shell'] }
        end

        describe directory "#{user_attr['home']}/.ssh" do
          it { should exist }
          its('owner') { should eq user_attr['username'] }
          its('group') { should eq user_attr['username'] }
          its('mode') { should cmp '0700' }
        end

        describe file "#{user_attr['home']}/.ssh/authorized_keys" do
          it { should exist }
          its('owner') { should eq user_attr['username'] }
          its('group') { should eq user_attr['username'] }
          its('mode') { should cmp '0600' }
        end

        describe cron(user: 'root') do
          it { should exist }
          it { should have_entry "30 0 * * 3 echo #{user_attr['username']}:$(openssl rand -base64 24) | chpasswd" }
        end
      end
    else
      puts 'There are no managed users. Nothing to test...'
    end

    describe group('service_users') do
      it { should exist }
      its('gid') { should eq 1131 }
      its('members') { should include(*node['stmtdb']['ssh_users'].map { |u| u['username'] }) }
    end

    directories = %w(
      /mnt/data/extract-sales
      /mnt/data/extract-sales/outfile
    )

    directories.each do |dir|
      describe directory dir do
        it { should exist }
        its('owner') { should eq 'root' }
        its('group') { should eq 'service_users' }
        its('mode') { should cmp '0770' }
      end
    end

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