#!/bin/bash
# provisioning {{provisioning_vers}} aws server creation: {{now}}
{% if use_debug %} set -x {% endif %}
aws_version=$(aws --version | cut -f1 -d" " | sed 's,aws-cli/,,g')
[ -z "$aws_version" ] && echo "Error❗: aws command as not found" && exit 1
if [ -z "$(aws configure get aws_access_key_id 2>/dev/null)" ] ; then 
  echo "Error❗ AWS credentials not found for command. Review $HOME/.aws/credentials and/or environment variables for settings" 
  exit 1
fi 
out_path={{runset.output_path}}
if [ -n "$out_path" ] ; then
  out_path=${out_path//NOW/{{now}}}
  [ ! -d "$out_path" ] && mkdir -p "$out_path"
else 
  out_path=/tmp
fi
{%- if server.hostname %}
instance_data=$(aws ec2 describe-instances --filter "Name=tag-value,Values={{server.hostname}}" "Name=instance-state-name,Values=running" \
--query "Reservations[*].Instances[].{\
__tags: Tags[?Key=='Name'].Value[],\
__id: InstanceId,\
__priv: NetworkInterfaces[*].PrivateIpAddresses[*].PrivateIpAddress,\
__pub: PublicIpAddress,\
__type: InstanceType,\
__status: State.Name\
}"\
 --output yaml 
)
instance_id=$(echo $instance_data | tr "__" "\n"  | grep "^id: " | cut -f2 -d":" | sed "s/ //g")
if  [ -n "$instance_id" ] ; then 
  instance_type=$(echo $instance_data | tr "__" "\n"  | grep "^type: " | cut -f2 -d":" | sed "s/ //g")
  status=$(echo $instance_data | tr "__" "\n"  | grep "^status: " | cut -f2 -d":" | sed "s/ //g")
  public_ip=$(echo $instance_data | tr "__" "\n"  | grep "^pub: " | cut -f2 -d":" | sed "s/ //g")
  echo -e "Server {{server.hostname}} already created \nid:    $instance_id\ntype:  $instance_type\nstate: $status\nip:    $public_ip " 
else
  interface=$(aws ec2 describe-network-interfaces --query "NetworkInterfaces[][NetworkInterfaceId,PrivateIpAddress]" --output text | grep  "{{server.network_private_ip}}" | awk '{print $1}')
  if [ -n "$interface" ] ; then 
    echo "Try to delete interface $interface already using {{server.network_private_ip}} ..." 
    aws ec2 delete-network-interface --network-interface-id "$interface"
    interface=$(aws ec2 describe-network-interfaces --query "NetworkInterfaces[][NetworkInterfaceId,PrivateIpAddress]" --output text | grep  "{{server.network_private_ip}}" | awk '{print $1}')
  fi
  [ -n "$interface" ] && echo "interface $interface is already using {{server.network_private_ip}}" && exit 1
  {% if use_time and use_time == 'true'  %} time {%- endif -%}
  aws ec2 run-instances \
  {%- if provider and provider.main and provider.main.subnet %}
  --subnet-id {{provider.main.subnet}} \
  {%- endif -%}
  {%- if provider and provider.main and provider.main.sg and provider.main.sg.id %}
  --security-group-ids {{provider.main.sg.id}} \
  {%- endif -%}
  {%- if server.ssh_key_name %}
  --key-name {{server.ssh_key_name}} \
  {%- elif defaults.ssh_key_name and defaults.ssh_key_name != '' %}
  --key-name {{defaults.ssh_key_name}} \
  {%- endif -%}
  {%- if server.plan %}
  --instance-type {{server.plan}} \
  {%- endif -%}
  {%- if server.storage_os %}
  --image-id {{server.storage_os}} \
  {%- endif -%}
  {%- if server.storages %} 
  --block-device-mappings '[
  {%- for storage in server.storages %}{%- if loop.index0 == 0 -%}{%- continue %}{%- endif -%}{%- if loop.index0 > 1 -%},{%- endif -%}
  {"DeviceName":"/dev/{{storage.voldevice}}","Ebs":{"VolumeSize":
  {%- if storage.size > 0 -%}{{storage.size}}{%- elif storage.parts and storage.parts[0] -%}{{storage.parts[0].size}}{%- endif -%},
  {%- if storage.encrypted -%}"Encrypted":{{storage.encrypted}},{%- endif -%}
  {%- if storage.kms_id and storage.kms_id != "" -%}"KmsKeyId":{{storage.kms_id}},{%- endif -%}
  "VolumeType":"{{storage.voltype}}","DeleteOnTermination":{{storage.deletetermination}}},"NoDevice":""}
  {%- endfor -%}]' \
  {%- endif -%}
  {%- if server.user_data %}
  --user-data {{server.user_data}} \
  {%- endif -%}
  {%- if server.disable_stop %}
  --disable-api-stop \
  {%- endif -%}
  {%- if server.zone %}
  --region {{server.zone}} \
  {%- endif %}
  --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value={{server.hostname}}},{Key=hostname,Value={{server.hostname}}}]' 'ResourceType=volume,Tags=[{Key=Name,Value={{server.hostname}}}]' \
  --output yaml > $out_path/{{server.hostname}}.yaml
  instance_id=$(grep "InstanceId:" $out_path/{{server.hostname}}.yaml | cut -f2 -d':')
  [ -z "$instance_id" ]  && echo "❗ Error: no instance id found for {{server.hostname}} " && exit 1
  {%- if provider and provider.priv and provider.priv.subnet and server.network_private_ip != '' %}
  while [ "$(aws ec2 describe-instance-status --instance-id $instance_id --query "InstanceStatuses[].InstanceState.Name" --out text)" != "running" ] ; do  sleep 10; echo "wait {{server.hostname}} running ..."; done
  interface=$(aws ec2 create-network-interface --subnet-id "{{provider.priv.subnet}}" --description "private_ip {{server.hostname}}" \
    --private-ip-address "{{server.network_private_ip}}" --query "NetworkInterface.NetworkInterfaceId" \
    {% if provider and provider.priv and provider.priv.sg and provider.priv.sg.id %}--groups {{provider.priv.sg.id}} {%- endif -%}  \
    --output text)
  [ -n "$interface" ] && [ -n "$instance_id" ] && aws ec2 attach-network-interface --network-interface-id $interface --instance-id $instance_id  --device-index 1
  {% endif %}
fi
{%- endif -%}
