require 'spec_helper'
require 'ec2ssh/command/update'
require 'ec2ssh/exceptions'

describe Ec2ssh::Command::Update do
  include FakeFS::SpecHelpers

  describe '#run' do
    let(:command) do
      described_class.new(cli).tap do |cmd|
        allow(cmd).to receive(:options).and_return(options)
        allow(cmd.builder).to receive(:aws_keys) { aws_keys }
        allow(cmd.builder.ec2s).to receive(:instances) { instances }
      end
    end
    let(:options) do
      double(:options, path: '/ssh_config', dotfile: '/dotfile', aws_key: 'default')
    end
    let(:cli) do
      double(:cli, options: options, red: nil, yellow: nil, green: nil)
    end
    let(:aws_keys) do
      {'default' => {'us-west-1' => Aws::Credentials.new('access_key_id', 'secret_access_key')}}
    end
    let(:instances) do
      [
        double('instance', private_ip_address: '10.0.0.1').tap {|m| allow(m).to receive(:tag).with('Name').and_return('srv1') },
        double('instance', private_ip_address: '10.0.0.2').tap {|m| allow(m).to receive(:tag).with('Name').and_return('srv2') }
      ]
    end

    before do
      File.open('/ssh_config', 'w') {|f| f.write ssh_config_str }
      File.open('/dotfile', 'w') {|f| f.write dotfile_str }
    end

    context 'with unmarked ssh_config' do
      let(:ssh_config_str) { '' }
      let(:dotfile_str) { <<-END }
path '/dotfile'
profiles 'default'
regions 'us-west-1'
host_line <<EOS
Host <%= tag('Name') %>
  HostName <%= private_ip_address %>
EOS
      END

      it do
        expect { command.run }.to raise_error(Ec2ssh::MarkNotFound)
      end
    end

    context 'with marked ssh_config' do
      let(:ssh_config_str) { <<-END }
# before lines...

### EC2SSH BEGIN ###
### EC2SSH END ###

# after lines...
      END

      let(:dotfile_str) { <<-END }
path '/dotfile'
profiles 'default'
regions 'us-west-1'
host_line <<EOS
Host <%= tag('Name') %>
  HostName <%= private_ip_address %>
EOS
      END

      before do
        Timecop.freeze(Time.utc(2014,1,1)) do
          command.run
        end
      end

      it do
        expect(File.read('/ssh_config')).to eq(<<-END)
# before lines...

### EC2SSH BEGIN ###
# Generated by ec2ssh http://github.com/mirakui/ec2ssh
# DO NOT edit this block!
# Updated 2014-01-01T00:00:00Z
# section: default
Host srv1
  HostName 10.0.0.1
Host srv2
  HostName 10.0.0.2
### EC2SSH END ###

# after lines...
        END
      end
    end
  end
end
