---
- name: Install prerequis
  ansible.builtin.apt:
    name:
      - build-essential
      - libz-dev
      - libreadline-dev
      - nodejs
      - nginx
    state: present

- name: Become zextras-ci user
  become: true
  become_user: zextras-ci
  block:
    - name: Find out if ruby is initialized
      ansible.builtin.stat:
        path: /home/zextras-ci/.rbenv/versions/{{ ruby_version }}
      register: ruby_version_install

    - name: Get rbenv from github
      ansible.builtin.git:
        repo: https://github.com/sstephenson/rbenv.git
        dest: /home/zextras-ci/.rbenv
        single_branch: true
        version: master
      when: not ruby_version_install.stat.exists

    - name: Get ruby build plugin for rbenv from github
      ansible.builtin.git:
        repo: https://github.com/sstephenson/ruby-build.git
        dest: /home/zextras-ci/.rbenv/plugins/ruby-build
        single_branch: true
        version: master
      when: not ruby_version_install.stat.exists

    - name: Install ruby with rbenv
      ansible.builtin.command: /home/zextras-ci/.rbenv/bin/rbenv install {{ ruby_version }}
      when: not ruby_version_install.stat.exists

    - name: Init rbenv in bashrc
      ansible.builtin.lineinfile:
        path: /home/zextras-ci/.bashrc
        line: 'eval "$(/home/zextras-ci/.rbenv/bin/rbenv init - bash)"'

    - name: Get setup version of ruby
      ansible.builtin.command: /home/zextras-ci/.rbenv/bin/rbenv global
      register: ruby_version_set
      changed_when: false
      check_mode: false

    - name: Set version ruby with rbenv
      ansible.builtin.command: /home/zextras-ci/.rbenv/bin/rbenv global {{ ruby_version }}
      when: not ruby_version_set.stdout == ruby_version

    - name: Install bundler
      ansible.builtin.command: /home/zextras-ci/.rbenv/versions/{{ ruby_version }}/bin/gem install bundler
      when: not ruby_version_set.stdout == ruby_version
