---
- block:
  - name: mastodon | Clone rbenv
    git:
      repo: "https://github.com/rbenv/rbenv.git"
      dest: "{{ mastodon_home }}/.rbenv"
      clone: true
     # version: "{{ rbenv_version }}"

  - name: mastodon | Configure rbenv
    command: ./configure
    args:
      chdir: "{{ mastodon_home }}/.rbenv/src"
    register: rbenv_configure

  - name: mastodon | Build rbenv
    command: make
    args:
      chdir: "{{ mastodon_home }}/.rbenv/src"
    when: rbenv_configure is succeeded

  - name: mastodon | Update profile settings
    blockinfile:
      dest: "{{ mastodon_home }}/.profile"
      content: |
        export PATH="{{ mastodon_home }}/.rbenv/bin:${PATH}"
        eval "$(rbenv init -)"

  - name: mastodon | Clone ruby-build
    git:
      repo: "https://github.com/rbenv/ruby-build.git"
      dest: "{{ mastodon_home }}/.rbenv/plugins/ruby-build"
      clone: true
      version: "{{ ruby_build_version }}"
    register: ruby_build

  - name: mastodon | Check if the Ruby version is already installed
    shell: "{{ mastodon_home }}/.rbenv/bin/rbenv versions | grep -q {{ ruby_version }}"
    register: ruby_installed
    ignore_errors: yes
    check_mode: no

  - name: mastodon | Install Ruby {{ ruby_version }}
    shell: "RUBY_CONFIGURE_OPTS=--with-jemalloc {{ mastodon_home }}/.rbenv/bin/rbenv install {{ ruby_version }}"
    args:
      executable: /bin/bash
    when: ruby_installed is failed

  - name: mastodon | Set the default Ruby version to {{ ruby_version }}
    shell: "{{ mastodon_home }}/.rbenv/bin/rbenv global {{ ruby_version }}"
    args:
      executable: /bin/bash
    register: default_ruby_version

  - name: mastodon | Install bundler
    shell: 'export PATH="$HOME/.rbenv/bin:$PATH"; eval "$(rbenv init -)"; gem install bundler:{{ bundler_version }}'
    args:
      executable: /bin/bash
    when: default_ruby_version is succeeded

  become: true
  become_user: "{{ mastodon_user }}"