---
- name: Add PHP PPA repository
  apt_repository:
    repo: "ppa:ondrej/php"
    update_cache: true

- name: Remove Old PHP Libraries
  apt:
    name: "{{ packages }}"
    state: absent
  vars:
    packages:
      - "php5-*"
      - "php7.0-*"
      - "php7.1-*"
      - "php7.2-*"
      - "php7.4-*"
      - "php8.0-*"
  ignore_errors: true

- name: Set PHP Version
  set_fact:
    php_version: 8.1

- name: "Install PHP {{ php_version }}"
  apt:
    name: "{{ packages }}"
    state: present
  vars:
    packages:
      - "php{{ php_version }}-fpm"
      - "php{{ php_version }}-cli"
      - "php{{ php_version }}-gd"
      - "php{{ php_version }}-curl"
      - "php{{ php_version }}-xml"         # IceCast XML config
      - "php{{ php_version }}-zip"         # Composer installs
      - "php{{ php_version }}-mysqlnd"     # MySQL Native Driver (Doctrine)
      - "php{{ php_version }}-mbstring"    # Codeception Tests
      - "php{{ php_version }}-intl"        # Localization
      - "php{{ php_version }}-redis"       # Cache
      - "php{{ php_version }}-bcmath"      # BigInteger
      - "php{{ php_version }}-gmp"         # BigInteger and PHP-IP
      - "php{{ php_version }}-maxminddb"   # Maxmind (GeoIP) DB native ext

- name: Configure PHP FPM Pool
  template:
    src: fpmpool.j2
    dest: "/etc/php/{{ php_version }}/fpm/pool.d/www.conf"
    force: true
    mode: 0644

- name: Configure php-fpm php.ini
  ini_file:
    dest: "/etc/php/{{ php_version }}/fpm/php.ini"
    section: PHP
    option: "{{ php_init_option.option }}"
    value: "{{ php_init_option.value }}"
    mode: 0644
  loop:
    - option: "post_max_size"
      value: "50M"
    - option: "short_open_tag"
      value: "On"
    - option: "upload_max_filesize"
      value: "50M"
  loop_control:
    loop_var: php_init_option

- name: Configure php-cli php.ini
  ini_file:
    dest: "/etc/php/{{ php_version }}/cli/php.ini"
    section: PHP
    option: "short_open_tag"
    value: "On"
    mode: 0644

- name: Install PHP-FPM Supervisord conf
  template:
    src: supervisor.conf.j2
    dest: /etc/supervisor/conf.d/php-fpm.conf
    force: true
    mode: 0644

- name: Disable PHP-FPM service
  service:
    name: "php8.1-fpm"
    enabled: false
    state: stopped
  ignore_errors: true
