---

- name: Install apg
  apt:
    name: apg

- name: Install phpmyadmin (Debian <=9)
  apt:
    name: phpmyadmin
  when: ansible_distribution_major_version is version('9', '<=')

- include_role:
    name: evolix/remount-usr

# /!\ Warning: this is a temporary hack as phpmyadmin for Buster is not yet
# available
- name: Install phpmyadmin using sid package (Debian >=10)
  apt:
    deb: http://mirror.evolix.org/debian/pool/main/p/phpmyadmin/phpmyadmin_4.6.6-4_all.deb
  when: ansible_distribution_major_version is version('10', '>=')

- name: Check if phpmyadmin default configuration is present
  stat:
    path: /etc/apache2/conf-enabled/phpmyadmin.conf
  register: pma_default_config

- debug:
    var: pma_default_config
    verbosity: 1

- name: Disable phpmyadmin default configuration
  command: "a2disconf phpmyadmin"
  register: command_result
  changed_when: "'Disabling' in command_result.stderr"
  when: pma_default_config.stat.exists

- name: "phpmyadmin suffix dirname '{{ packweb_phpmyadmin_suffix_file | dirname }}' exists"
  file:
    dest: "{{ packweb_phpmyadmin_suffix_file | dirname }}"
    mode: "0700"
    owner: root
    group: root
    state: directory

- name: set phpmyadmin suffix if provided
  copy:
    dest: "{{ packweb_phpmyadmin_suffix_file }}"
    # The last character "\u000A" is a line feed (LF), it's better to keep it
    content: "{{ packweb_phpmyadmin_suffix }}\u000A"
    force: yes
  when: packweb_phpmyadmin_suffix != ""

- name: generate random string for phpmyadmin suffix
  shell: "apg -a 1 -M N -n 1 > {{ packweb_phpmyadmin_suffix_file }}"
  args:
    creates: "{{ packweb_phpmyadmin_suffix_file }}"

- name: read phpmyadmin suffix
  command: "tail -n 1 {{ packweb_phpmyadmin_suffix_file }}"
  changed_when: False
  check_mode: no
  register: new_packweb_phpmyadmin_suffix

- name: overwrite packweb_phpmyadmin_suffix
  set_fact:
    packweb_phpmyadmin_suffix: "{{ new_packweb_phpmyadmin_suffix.stdout }}"

- debug:
    var: packweb_phpmyadmin_suffix
    verbosity: 1

- name: enable phpMyAdmin config
  blockinfile:
    dest: /etc/apache2/sites-available/000-evolinux-default.conf
    marker: "# {mark} phpMyAdmin section"
    block: |
      Alias /phpmyadmin /var/www
      Alias /phpmyadmin-{{ packweb_phpmyadmin_suffix }} /usr/share/phpmyadmin/
      Include /etc/phpmyadmin/apache.conf
      <Directory /usr/share/phpmyadmin/>
          Require all denied
          Include /etc/apache2/ipaddr_whitelist.conf
      </Directory>

- name: enable phpmyadmin link in default site index
  replace:
    dest: /var/www/index.html
    regexp:  '<!-- <li><a href="/phpmyadmin-__PHPMYADMIN_SUFFIX__/">Accès PhpMyAdmin</a></li> -->'
    replace: '     <li><a href="/phpmyadmin-__PHPMYADMIN_SUFFIX__/">Accès PhpMyAdmin</a></li>'

- name: replace phpmyadmin suffix in default site index
  replace:
    dest: /var/www/index.html
    regexp: '__PHPMYADMIN_SUFFIX__'
    replace: "{{ packweb_phpmyadmin_suffix }}"
