class Envirobly::ContainerShell

def connect

def connect
  api = Envirobly::Api.new
  response = api.create_service_shell_connection @params
  ssh_params = response.object
  Tempfile.create do |tempkey|
    tempkey.write ssh_params.fetch("instance").fetch("private_key")
    tempkey.flush
    cmd = sprintf(
      CMD_TEMLATE,
      ssh_params.fetch("open_tunnel_credentials").fetch("access_key_id"),
      ssh_params.fetch("open_tunnel_credentials").fetch("secret_access_key"),
      ssh_params.fetch("open_tunnel_credentials").fetch("session_token"),
      tempkey.path,
      ssh_params.fetch("instance").fetch("private_ipv4"),
      ssh_params.fetch("instance").fetch("aws_id"),
      ssh_params.fetch("region")
    )
    if @options.shell.present?
      cmd = "ENVIROBLY_SERVICE_INTERACTIVE_SHELL='#{@options.shell}' #{cmd} -o SendEnv=ENVIROBLY_SERVICE_INTERACTIVE_SHELL"
    end
    if @options.user.present?
      cmd = "ENVIROBLY_SERVICE_SHELL_USER='#{@options.user}' #{cmd} -o SendEnv=ENVIROBLY_SERVICE_SHELL_USER"
    end
    if @command.present?
      cmd = "#{cmd} #{@command.join(" ")}"
    end
    system cmd
  end
end

def initialize(service_name, command, options)

def initialize(service_name, command, options)
  @command = command
  @options = options
  commit = Envirobly::Git::Commit.new "HEAD"
  @params = {
    project: {
      account_id: options.account_id || Envirobly::Defaults::Account.new.id,
      name: options.project_name || File.basename(Dir.pwd), # TODO: Extract into Defaults::ProjectName
      id: options.project_id
    },
    environ: { name: options.environ_name || commit.current_branch },
    service: { name: service_name },
    instance: { slot: options.instance_slot }
  }
  if options.project_name.blank? && options.account_id.blank? && options.project_id.blank?
    @params[:project][:id] = Envirobly::Defaults::Project.new.id
  end
end