---
# Create a NetBSD/EC2 instance and get it to basic state
#
# Assumes:
#  - ec2-webservers group
#  - all $EC2... variables set
#
# Run:
#    ansible-playbook -i hosts-HF config-ec2-prepare1vm.yml
#
# More information: http://wiki.centos.org/Cloud/Manage/Ansible
#
# Copyright (c) 2013 Hubert Feyrer <hubert@feyrer.de>
#

 - hosts:
   - localhost
   connection: local
   gather_facts: false
   vars:
      keypair: eucaHF
      instance_type: t1.micro
      security_group: ec2-webservers
      image: ami-5d0f8034
      #image: ami-5d0f8034	= NetBSD-i386-6.0.1-20121228-0908
      #image: ami-a754dbce	= NetBSD-x86_64-6.0.1-20121227-1659 
      mail_from: Ansible
      mail_to: hubertf@NetBSD.org

   tasks:
    - name: Launch new EC2 instance
      local_action: ec2
         keypair=${keypair}
         group=${security_group}
         instance_type=${instance_type}
         image=${image}
         wait=true
      register: ec2

    - name: Give the system 30 seconds to boot up
      local_action: command sleep 30

    - name: Get rid of SSH "Are you sure you want to continue connecting (yes/no)?" query
      local_action: command sh -c 'ssh-keyscan -t rsa ${ec2.instances[0].public_ip} >>$HOME/.ssh/known_hosts'

    - name: Fix /usr/bootstrap.sh to run pkgin with -y
      local_action: command ssh root@${ec2.instances[0].public_ip} '${item.cmd}'
      with_items:
       - { cmd: "install /usr/bootstrap.sh /usr/bootstrap.sh.orig" }
       - { cmd: "chmod +w /usr/bootstrap.sh" }
       - { cmd: "sed \"s,bin/pkgin update,bin/pkgin -y update,\" </usr/bootstrap.sh.orig >/usr/bootstrap.sh" }
       - { cmd: "chmod -w /usr/bootstrap.sh" }

    - name: Install pkgin via /usr/bootstrap.sh
      local_action: command ssh root@${ec2.instances[0].public_ip} '${item.cmd}'
      with_items:
       - { cmd: "env PATH=/usr/sbin:${PATH} /usr/bootstrap.sh binpkg" }

    - name: Copy over Ansible binary package
      local_action: command scp files/ansible-1.0.tgz root@${ec2.instances[0].public_ip}:/tmp

    - name: Install Ansible dependencies
      local_action: command ssh root@${ec2.instances[0].public_ip} '/usr/sbin/pkg_info -qn /tmp/ansible-1.0.tgz | sed -e "s,\[[^]]*\],," -e "s,[->][^->]*\$,," | xargs -n 1 echo /usr/pkg/bin/pkgin -y install | sh -vx'

    - name: Install Ansible package (manually)
      local_action: command ssh root@${ec2.instances[0].public_ip} '/usr/sbin/pkg_add /tmp/ansible-1.0.tgz'

    - name: Setup lame /usr/bin/python symlink
      local_action: command ssh root@${ec2.instances[0].public_ip} 'ln -s /usr/pkg/bin/python2.7   /usr/bin/python'

#   - name: Send mail to admin
#     local_action: mail
#     from=${mail_from}
#     to=${mail_to}
#     subject="New EC2 instance ${ec2.instances[0].id}""
#     body="EC2 instance ${ec2.instances[0].id} created on ${ec2.instances[0].public_ip}"
