# Ansible playbook to add in the intermuse site and interface
# to a GS3 base installation, along with its supporting
# dependencies

# See greenstone3-svn-base-playbook.yml for details on how to run
---

- name:       Setting up variables for installation of the GS3 Extension structured-image
  hosts:      localhost
  connection: local

  vars_files:
    - vars/default-core.yml

  tasks:
    - name: Setting Greenstone3 username
      set_fact: gsdl3_user="{{ ansible_user | default(ansible_env.USER,true) | default('greenstone',true) }}"
    - debug: msg="gsdl3_user = {{ gsdl3_user }}"


- name:       Installing GS3 Extension(s)
  hosts:      localhost
  connection: local
  become_user: "{{ gsdl3_user }}"
  become:     true

  vars_files:
    - vars/default-core.yml

  tasks:
  - name: Downloading and unpacking self-contained command-line tools for structured-image extension
    ansible.builtin.shell:
      chdir:     "{{ gsdl3srchome }}/ext-cli"
      cmd:       "./get-selfcontained-{{ item }}.sh"
    register:  result
    changed_when:
      - '"Untarred" in result.stdout'      
    with_items:
      - mvn

  
  # The next two steps are equivalent to sourcing gs3-setup.sh
  # For more details, see:
  #   https://stackoverflow.com/questions/60209185/ansible-environment-variables-from-env-file
  #
  - name: Source Greenstone3's gs3-setup.sh
    ansible.builtin.shell:
      executable: /bin/bash
      chdir:      "{{ gsdl3srchome }}"
      # RHEL8.5 introduces a weirdly environemnt variable BASH_FUNC_which%% set to a multi-line JSON value
      # => use 'sed' to delete this form 'env' output
      cmd:        . ./gs3-setup.sh 1>/dev/null 2>&1 && env | sed '/^BASH_FUNC_which%%=() {.*$/,/^}$/d'
    register:   env_file_result

  #- debug: var=env_file_result.stdout_lines

  - name: Parse Greenstone3 environment variables
    set_fact:
      env_vars: "{{ ('{' + env_file_result.stdout_lines | map('regex_replace', '([^=]*)=(.*)', '\"\\1\": \"\\2\"') | join(',') + '}') | from_json }}"

  #- debug: var=env_vars

  # !!!!
  # Leaving as a 'for-each' extension in case this is useful further down the line
  # !!!!

  - name: Svn checking out GS3 extensions
    ansible.builtin.shell:
      chdir:     "{{ gsdl3srchome }}/ext"
      cmd:       "./get-extension.sh {{ item }}"
    register:  result
    changed_when:
      - '"A    " | string in result.stdout'      
    with_items:
      - structured-image 

  - name: Compiling and Installing the structured-image extension
    ansible.builtin.command:
      chdir: "{{ gsdl3srchome }}/ext/structured-image"
      cmd: ./CASCADE-COMPILE-AND-INSTALL.sh
    environment: "{{ env_vars }}"


