---
- name: (Prod) Generate MariaDB User Password
  command: pwgen 8 -sn 1
  register: prod_mysql_user_password
  when: app_env == "production"

- name: Assign User Password
  set_fact:
    mysql_user_password: "{{ prod_mysql_user_password.stdout if app_env == 'production' else dev_mysql_user_password }}"

- name: Add configuration
  template: src=my.cnf.j2 dest=/etc/mysql/conf.d/my.cnf owner=root group=root mode=0644

- name: Add empty root .my.cnf (if none exists)
  template: src=root_empty_my.cnf.j2 dest=/root/.my.cnf owner=root group=root mode=0600 force=no

- name: MariaDB Cleanup
  command: >-
    mysql --defaults-extra-file=/root/.my.cnf -ne "{{ azure_db_install_sql_cleanup_query }}"
  loop:
    - "DELETE FROM mysql.user WHERE User=''"
    - "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1')"
    - "DROP DATABASE test"
    - "DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%'"
  loop_control:
    loop_var: azure_db_install_sql_cleanup_query
  changed_when: false
  ignore_errors: true

# MySQL Secure Installation
- name: Set up AzuraCast database user
  mysql_user:
    name: azuracast
    host: "localhost"
    password: "{{ mysql_user_password }}"
    priv: "azuracast.*:ALL,GRANT"
    state: present
  notify: send mysql notification

- name: Add .my.cnf
  template:
    src: user_my.cnf.j2
    dest: "{{ app_base }}/.my.cnf"
    owner: azuracast
    group: www-data
    mode: 0644
    force: true

- name: Reload privilege tables
  command: >-
    mysql --defaults-extra-file=/root/.my.cnf -ne "FLUSH PRIVILEGES"
  changed_when: false

# Create Database
- name: Create MySQL Database
  mysql_db:
    config_file: "/root/.my.cnf"
    name: azuracast
    state: present
    collation: utf8mb4_unicode_ci
    encoding: utf8mb4
  register: azuracast_db_created

- name: Set up environment file
  ini_file:
    dest: "{{ www_base }}/env.ini"
    section: "configuration"
    option: "{{ azure_db_install_env_ini.option }}"
    value: "{{ azure_db_install_env_ini.value }}"
    mode: 0644
  loop:
    - option: 'MYSQL_HOST'
      value: 'localhost'
    - option: 'MYSQL_PORT'
      value: '3306'
    - option: 'MYSQL_USER'
      value: 'azuracast'
    - option: 'MYSQL_DB'
      value: 'azuracast'
    - option: 'MYSQL_PASSWORD'
      value: "{{ mysql_user_password }}"
  loop_control:
    loop_var: azure_db_install_env_ini
