---

- name: Set filename from current date & time
  set_fact:
    config_date_time: "{{ ansible_date_time.date }}_{{ ansible_date_time.hour }}-{{ ansible_date_time.minute }}-{{ ansible_date_time.second }}"

- name: Install a list of packages
  ansible.builtin.apt:
    update_cache: yes
    state: present
    pkg:
    - curl
    - openssh-server
    - ca-certificates
    - tzdata
    - perl
    - gnupg
    - apt-transport-https

- name: Install Debian archive keyring
  ansible.builtin.apt:
    update_cache: yes
    state: present
    pkg:
    - debian-archive-keyring
  when: ansible_distribution == 'Debian'

- name: Add an Apt signing key, uses whichever key is at the URL
  ansible.builtin.apt_key:
    url: https://packages.gitlab.com/gitlab/gitlab-ce/gpgkey
    state: present

- name: Add specified repository into sources list
  ansible.builtin.apt_repository:
    repo: deb https://packages.gitlab.com/gitlab/gitlab-ce/{{ ansible_distribution | lower }}/ {{ ansible_distribution_release | lower }} main
    filename: gitlab_gitlab-ce
    state: present

- name: Install gitlab-ce
  ansible.builtin.apt:
    update_cache: yes
    state: present
    pkg:
    - gitlab-ce

- name: Create a directory for config backups
  ansible.builtin.file:
    path: "/opt/gitlab.rb"
    state: directory
    owner: root
    group: root
    mode: '0755'

- name: Populate gitlab config
  ansible.builtin.copy:
    content: |
      {{ gitlab_config }}
    dest: "/etc/gitlab/gitlab.rb/"
    owner: root
    group: root
    mode: '0644'
    backup: yes
  register: gitlab_config
  notify: Reconfigure gitlab

- debug: var=gitlab_config.backup_file

- name: Backup previous gitlab config
  ansible.builtin.copy:
     dest: "/opt/gitlab.rb"
     src: "{{ gitlab_config.backup_file }}"
     remote_src: true
  when: gitlab_config.changed

- name: Remove backup file from gitlab config dir
  ansible.builtin.file:
    path: "{{ gitlab_config.backup_file }}"
    state: absent
  when: gitlab_config.changed
