# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure('2') do |config|
  config.vm.provider :aws do |provider|
    # set unique vm name
    provider.tags = {
      'Name' => VM_NAME
    }

    provider.access_key_id = ENV['AWS_ACCESS_KEY_ID']
    provider.secret_access_key = ENV['AWS_SECRET_ACCESS_KEY']
    provider.keypair_name = ENV['AWS_KEYPAIR_NAME']
    provider.security_groups = 'salted_server'
    provider.availability_zone = 'us-west-1c'
    provider.region = 'us-west-1'
    provider.ami = get_env_var_rb('ami') ? get_env_var_rb('ami') :
                     SETTINGS['GUEST_OSES'][SETTINGS['GUEST_OSES_DEFAULT']]['ec2']

    if get_env_var_rb('machinetype')
      provider.instance_type = get_env_var_rb('machinetype')
    elsif get_env_var_rb('ramsize') == '512'
      provider.instance_type = 't2.nano'
    elsif get_env_var_rb('ramsize') == '1024'
      provider.instance_type = 't2.micro'
    elsif get_env_var_rb('ramsize') == '2048'
      provider.instance_type = 't2.small'
    elsif get_env_var_rb('ramsize') == '4096'
      provider.instance_type = 't2.medium'
    elsif get_env_var_rb('ramsize') == '8192'
      provider.instance_type = 't2.large'
    end

    if (get_env_var_rb('guest_os') != 'debian-9') && (get_env_var_rb('guest_os') != 'debian-8')
      provider.block_device_mapping = [{
        'DeviceName' => '/dev/sda1',
        'Ebs.VolumeSize' => get_env_var_rb('drivesize'),
        'Ebs.VolumeType' => 'gp2',
        'Ebs.DeleteOnTermination' => 'true',
       }]
    end

    provider.user_data = '#!/bin/bash
      oldusers=( admin root ubuntu centos fedora ec2-user )
      for olduser in "${oldusers[@]}"; do
        if grep -q $olduser "/etc/sudoers.d/90-cloud-init-users"; then
          user=vagrant
          usermod  -l $user $olduser
          groupmod -n $user $olduser
          usermod  -d /home/$user -m $user
          sed -i "s/$olduser/vagrant/g" /etc/sudoers.d/90-cloud-init-users
        fi
      done
    '
  end
  config.ssh.username = 'vagrant'
  config.ssh.private_key_path = ENV['AWS_SSH_PRIVKEY']
  config.ssh.forward_agent = true

  config.vm.box = 'dummy'
  config.vm.box_url = 'https://github.com/mitchellh/vagrant-aws/raw/master/dummy.box'
end
