#
# wordpress-install-playbook.yml
#
# Ansible playbook that integrates WordPress (PHP-based) into an
# existing reverse-proxied Greenstone3 installation.
#
# This (install) playbook does:
#   (a) installs the command-line packages needed
#   (b) untars WordPress into the Apache web-root directory (as wordpress/)
#
# The next (configure) playbook does:
#   (c) uses 'wp' to configure the WordPress files
#
# End result:
#   https://{{ gsdl3servlet_external.domain }}/greenstone3/wordpress

---
- name: Configure WordPress within existing Apache/Greenstone3
  hosts: localhost
  connection: local
  gather_facts: true

  vars_files:
    - vars/default-core.yml
    - vars/default-wordpress.yml

  vars:
    site_name: "{{ apache2_revproxy_config.config_root_name }}"
    apache2_main_config_file: "/etc/apache2/sites-enabled/{{ site_name }}.conf"
    apache2_wordpress_topup_file: "sites-enabled/{{ site_name }}-wordpress-topup.conf"   # set absolute path if not in ServerRoot
    gsdl3_web_dir: "{{ gsdl3srchome }}/web"
    wordpress_dir: "{{ gsdl3_web_dir }}/wordpress"
    apachectl_bin: /usr/sbin/apache2ctl

  pre_tasks:
    - name: Check if community.general.apache2_module is available on controller
      ansible.builtin.command: ansible-doc -t module community.general.apache2_module
      register: apache2_module_doc
      ignore_errors: true
      changed_when: false
      delegate_to: localhost
      run_once: true

    - name: Install community.general if missing (controller-side)
      ansible.builtin.command: ansible-galaxy collection install community.general
      when: apache2_module_doc.rc != 0
      changed_when: "'Installing' in apache2_module_install.stdout | default('')"
      register: apache2_module_install
      delegate_to: localhost
      run_once: true

    - name: Recheck availability after install attempt
      ansible.builtin.command: ansible-doc -t module community.general.apache2_module
      register: apache2_module_doc_after
      ignore_errors: true
      changed_when: false
      delegate_to: localhost
      run_once: true

    - name: Set fact for apache2_module availability
      ansible.builtin.set_fact:
        apache2_module_available: "{{ apache2_module_doc_after.rc == 0 }}"

  tasks:
    - name: Debian/Ubuntu package setup
      ansible.builtin.include_tasks:
        file: wordpress-debian-task.yml
        apply:
          become: true
      when: ansible_distribution in ['Debian', 'Ubuntu']

    - name: Determine PHP version (major.minor)
      ansible.builtin.command: php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;'
      register: php_ver
      changed_when: false

    - name: Define PHP-FPM socket path
      ansible.builtin.set_fact:
        php_fpm_sock: "/run/php/php{{ php_ver.stdout }}-fpm.sock"

    - name: Add in Apache2 config topup file for WordPress
      become: true
      template:
        src: "files/apache-wordpress-topup.conf.j2"
        dest: "/etc/apache2/sites-enabled/{{ site_name }}-wordpress-topup.conf"

    - name: Enable required Apache modules (preferred - community.general.apache2_module)
      become: true
      community.general.apache2_module:
        name: "{{ item }}"
        state: present
      loop:
        - proxy
        - proxy_fcgi
        - setenvif
        - rewrite
      when: apache2_module_available | default(false)
      notify: Reload Apache2

    - name: Enable required Apache modules (fallback - a2enmod CLI)
      become: true
      ansible.builtin.command: "a2enmod {{ item }}"
      args:
        creates: "/etc/apache2/mods-enabled/{{ item }}.load"
      loop:
        - proxy
        - proxy_fcgi
        - setenvif
        - rewrite
      when: not (apache2_module_available | default(false))
      notify: Reload Apache2

    - name: Insert WordPress include after the marker
      become: true
      ansible.builtin.blockinfile:
        path: "{{ apache2_main_config_file }}"
        insertafter: '^\s*#Extra-Ansible-Injected#\s*$'
        marker: "# {mark} ANSIBLE-MANAGED-WORDPRESS-INCLUDE"
        block: |
          # Bring in WordPress config
          Include "{{ apache2_wordpress_topup_file }}"
        #validate: "{{ apachectl_bin }} -t -f %s"
      notify: Reload Apache2


    ## Check if WordPress is already installed
    - name: Check for existing WordPress installation/config file
      ansible.builtin.stat:
        path: "{{ wordpress_dir }}/wp-settings.php"
      register: wp_settings_check

    - name: Download and unpack WordPress archive if not present
      ansible.builtin.get_url:
        url: https://wordpress.org/wordpress-{{ wordpress_version }}.tar.gz
        dest: ./downloads/wordpress-{{  wordpress_version  }}.tar.gz
        mode: '0644' # Set standard file permissions
      when: not wp_settings_check.stat.exists
      
    ## Conditionally include the setup file
    - name: Execute WordPress file setup and configuration (if not already installed)
      ansible.builtin.include_tasks: wordpress-setup-files-task.yml
      when: not wp_settings_check.stat.exists 

    - name: WordPress URL
      ansible.builtin.debug:
        msg: |
          ****
          * WordPress has been installed in:
          *   {{ wordpress_dir }}
          * and the Apache2 web server has been updated to run PHP
          *
          * While the WordPress has been installed, it is yet to be configured
          * At this stage you can check the main WordPress in the browser
          * which will display a message notifying you that it has not yet
          * been configured!
          * 
          *   http://{{ gsdl3servlet_external.domain }}/wordpress/index.php
          ****

    - name: Ensure 'bin' directory exists
      ansible.builtin.file:
        path: bin
        state: directory
    
    - name: Download wp-cli.phar if not present
      ansible.builtin.get_url:
        url: https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
        dest: ./downloads/wp-cli.phar
        mode: '0755' # Set execution permissions (a+x)

    - name: Installing wp-cli.phar as bin/script/wp
      ansible.builtin.copy:
        src: ./downloads/wp-cli.phar
        dest: ./bin/script/wp
        mode: '0755' # Set execution permissions (a+x)

  handlers:
    - name: Reload Apache2
      become: true
      ansible.builtin.service:
        name: apache2
        state: reloaded

    - name: Restart Apache2
      become: true
      ansible.builtin.service:
        name: apache2
        state: restarted
