---
- name: Update APT cache
  apt: update_cache=yes
  become: true
  when: ansible_distribution == 'Debian' or ansible_distribution == 'Ubuntu'

- name: Retrieve the number of cores that are available for compilation
  command: nproc
  register: cores

- name: Install APT prerequisite packages that are necessary to compile applications and gems with native extensions
  apt: pkg={{ item }}
  become: true
  with_items:
    - autoconf
    - build-essential
  when: ansible_distribution == 'Debian' or ansible_distribution == 'Ubuntu'

- name: Install yum prerequisite packages that are necessary to compile applications and gems with native extensions
  yum: name="{{ item }}"
  become: true
  with_items:
    - autoconf
    - "@Developer tools"
  when: ansible_distribution == 'CentOS' or ansible_distribution == 'Red Hat Enterprise Linux' or ansible_distribution == 'Amazon'

- name: Install APT Ruby dependencies
  become: true
  apt: pkg={{ item }}
       state=present
  with_items: "{{ ruby_apt_dependencies }}"
  when: ansible_distribution == 'Debian' or ansible_distribution == 'Ubuntu'

- name: Install yum Ruby dependencies
  become: true
  yum: name={{ item }}
  with_items: "{{ ruby_yum_dependencies }}"
  when: ansible_distribution == 'CentOS' or ansible_distribution == 'Red Hat Enterprise Linux' or ansible_distribution == 'Amazon'

- name: Download the Ruby source code
  get_url: url={{ ruby_download_location }}
           dest=/usr/local/src/
           sha256sum={{ ruby_checksum }}
  become: true

- name: Generate the Ruby installation script
  template: src=install-ruby.j2
            dest=/usr/local/src/install-ruby.sh
            owner=root
            group=root
            mode=700
  become: true

- name: Run the Ruby installation script
  command: /usr/local/src/install-ruby.sh
           creates={{ ruby_location }}/bin/ruby
  become: true

- name: Generate the script that allows you to easily run Rake tasks with the correct RAILS_ENV environment variable, and the wrapper script that contains GC settings
  template: src={{ item }}.j2
            dest=/usr/local/bin/{{ item }}
            owner=root
            group=root
            mode=755
  become: true
  with_items:
    - rake-env
    - ruby-gc-wrapper

- name: Update rubygems
  command: "{{ ruby_location }}/bin/gem update --system"
  become: true

- name: Remove old bundler bin
  file:
    path: "{{ ruby_location }}/bin/bundle"
    state: absent
  become: true

- name: Uninstall Bundler
  gem:
    name: bundler
    state: absent
    user_install: no
    executable: "{{ ruby_location }}/bin/gem"
  become: true

- name: Install Bundler
  gem:
    name: bundler
    version: "{{ bundler_version }}"
    state: present
    user_install: no
    executable: "{{ ruby_location }}/bin/gem"
  become: true

- name: Make Ruby symlinks
  file: path=/usr/local/bin/{{ item }}
        src={{ ruby_location }}/bin/{{ item }}
        state=link
  become: true
  with_items: "{{ ruby_symlinks }}"