#jinja2:variable_start_string:'[%' , variable_end_string:'%]'
---
- name: check/create instance
  hosts: localhost
  user: copr
  gather_facts: False

  vars:
  - security_group: builder
  - OS_AUTH_URL: http://172.23.0.2:5000/v2.0
  - OS_TENANT_NAME: copr
  - OS_USERNAME: msuchy
  - OS_PASSWORD: [% copr_nova_password %]
  # rhel 6.4 2013-02-21 x86_64 - ami
  - image_id: cba0c766-84ac-4048-b0f5-6d4000af62f8

  tasks:
  - name: generate builder name
    local_action: command echo "Copr builder {{ 999999999 | random }}"
    register: vm_name

  - name: spin it up
    local_action: nova_compute auth_url={{OS_AUTH_URL}} flavor_id=6 image_id={{ image_id }} key_name=buildsys login_password={{OS_PASSWORD}} login_tenant_name={{OS_TENANT_NAME}} login_username={{OS_USERNAME}} security_groups={{security_group}} wait=yes name="{{vm_name.stdout}}"
    register: nova

  # should be able to use nova.private_ip, but it does not work with Fedora Cloud.
  - debug: msg="IP={{ nova.info.addresses.vlannet_3[0].addr }}"

  - debug: msg="vm_name={{vm_name.stdout}}"

  - name: add it to the special group
    local_action: add_host hostname={{ nova.info.addresses.vlannet_3[0].addr }} groupname=builder_temp_group

  - name: wait for the host to be hot
    local_action: wait_for host={{ nova.info.addresses.vlannet_3[0].addr }} port=22 delay=5 timeout=600

- hosts: builder_temp_group
  user: root
  gather_facts: False
  vars:
   - files: files/
  
  tasks:
  - name: edit hostname to be instance name
    action: shell hostname  `curl -s http://169.254.169.254/2009-04-04/meta-data/instance-id`

  - name: install pkgs
    action: yum state=present pkg={{ item }}
    with_items:
    - rsync
    - openssh-clients
    - libselinux-python
    - libsemanage-python

  - name: add repos
    action: copy src={{ files }}/{{ item }} dest=/etc/yum.repos.d/{{ item }}
    with_items:
    - builder.repo
    - epel6.repo

  - name: install additional pkgs
    action: yum state=present pkg={{ item }}
    with_items:
    - mock
    - createrepo
    - yum-utils
    - pyliblzma

  - name: make sure newest rpm
    action: yum name={{ item }} state=latest
    with_items:
    - rpm
    - glib2

  - yum: name=mock  enablerepo=epel-testing state=latest

  - name: mockbuilder user   
    action: user name=mockbuilder groups=mock

  - name: mockbuilder .ssh
    action: file state=directory path=/home/mockbuilder/.ssh mode=0700 owner=mockbuilder group=mockbuilder

  - name: mockbuilder authorized_keys
    action: authorized_key user=mockbuilder key='{{ lookup('file', '/home/copr/provision/files/buildsys.pub') }}'

  - name: put updated mock configs into /etc/mock
    action: copy src={{ files }}/mock/{{ item }} dest=/etc/mock
    with_items:
    - site-defaults.cfg
    - epel-5-x86_64.cfg
    - epel-5-i386.cfg
    - fedora-20-x86_64.cfg
    - fedora-20-i386.cfg
    - epel-7-x86_64.cfg

  - lineinfile: dest=/root/.bashrc line="ulimit -n 10240" insertafter=EOF
