---
- name: Ensure custom facts directory exists
  file:
    mode: 0755
    path: /etc/ansible/facts.d
    state: directory

- name: "Fetch {{ app_name }}'s releases page"
  uri:
    url: https://gitlab-runner-downloads.s3.amazonaws.com/latest/index.html
    return_content: true
  register: gitlab_runner_latest_release_page

- name: "Detect the latest {{ app_name }} version"
  set_fact:
    gitlab_runner_latest_release_tag: "{{ gitlab_runner_latest_release_page.content | regex_search(' v(\\d*\\.)*\\d*') | replace(' v', '') }}"

- name: "Determine whether or not the latest version of {{ app_name }} is already installed"
  set_fact:
    install_gitlab_runner: "{{ (ansible_local.gitlabrunner is not defined) or \
      ((ansible_local.gitlabrunner is defined) and \
      (ansible_local['gitlabrunner']['settings']['version'] != gitlab_runner_latest_release_tag)) }}"

- name: "Find the Checksum of {{ app_name }} installer"
  set_fact:
    gitlab_runner_checksum: "{{ gitlab_runner_latest_release_page.content | regex_search('((gitlab-runner-linux-amd64.*\\n.*checksum).{2}).*<') |\
     regex_replace('((gitlab-runner-linux-amd64.*\\n.*checksum).{2})(?P<checksum>.*)<', '\\g<checksum>') }}"
  when: install_gitlab_runner

- name: "Ensure {{ app_name }} is installed"
  get_url:
    url: "https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-linux-amd64"
    dest: /usr/local/bin
    mode: 0755
    checksum: "sha256:{{ gitlab_runner_checksum }}"
  when: install_gitlab_runner

- name: "Save meta information about the version of {{ app_name }} that was installed"
  community.general.ini_file:
    path: /etc/ansible/facts.d/gitlabrunner.fact
    mode: 0644
    section: settings
    option: version
    value: "{{ gitlab_runner_latest_release_tag }}"
    backup: true
    no_extra_spaces: true
  when: install_gitlab_runner
