---
  # "Install PL/Java."
    
  - name: "Add the PL/Java dependencies."
    apt:
       name: "{{ item }}"
       state: present
    with_items:
       - libecpg-dev
       - libkrb5-dev
       - maven
       - git
    
  - name: "Check if PL/Java already exists."
    stat:
       path: "/usr/share/postgresql/{{ pg_version }}/pljava/pljava-1.5.0.jar"
    register: plj_result
    
  - name: "Create a temporary directory."
    file:
       path: "{{ tmp_plj_dir }}"
       state: directory
    register: temp_result
    when: not (plj_result.stat.exists is defined and plj_result.stat.exists)
    
  - name: "Download the PL/Java 1.5.0 source project archive."
    get_url:
       url: "https://proj.goldencode.com/downloads/pljava/pljava_src_1_5_0.zip"
       dest: "{{ tmp_plj_dir }}"
    register: download_result
    when: temp_result.changed and temp_result|success
    
  - name: "Unzip the PL/Java 1.5.0 source project."
    command: unzip -q "{{ tmp_plj_dir }}/pljava_src_1_5_0.zip" -d "{{ tmp_plj_dir }}"
    # ansible 2.2 or later should be able to eliminate the separate download and unzip steps and
    # use the built-in module
    # unarchive:
    #    src: "https://proj.goldencode.com/downloads/pljava/pljava_src_1_5_0.zip"
    #    dest: "{{ tmp_plj_dir }}"
    #    remote_src: true
    register: unzip_result
    when: download_result.changed and download_result|success
    
  - name: "Build PL/Java."
    shell: mvn clean install
    args:
       chdir: "{{ tmp_plj_dir }}/pljava-1_5_0" 
    register: mvn_result
    when: unzip_result.changed and unzip_result|success
    
  - name: "Run the PL/Java installer."  
    shell: java -jar "pljava-packaging/target/pljava-pg{{ pg_version }}-amd64-Linux-gpp.jar"
    args:
       chdir: "{{ tmp_plj_dir }}/pljava-1_5_0"
    notify: "reload cluster"
    when: mvn_result.changed and mvn_result|success
       
  - name: "Modify postgresql.conf for PL/Java."  
    blockinfile:
       dest: "/etc/postgresql/{{ pg_version }}/{{ cluster_name }}/postgresql.conf"
       marker: "# {mark} FWD PL/Java Configuration"
       insertafter: EOF
       block: |
          pljava.libjvm_location = '/usr/lib/jvm/default-java/jre/lib/amd64/server/libjvm.so'
          pljava.classpath = '/usr/share/postgresql/{{ pg_version }}/pljava/pljava-1.5.0.jar'
          pljava.vmoptions = '-Xmx16m'
    notify: "reload cluster"
          
  - name: "Ensure the permissions of the PL/Java install directory are correct."
    file:
       path: "/usr/share/postgresql/{{ pg_version }}/pljava/"
       state: directory
       mode: 0755
    
  - name: "Remove the temporary directory."
    file:
       path: "{{ tmp_plj_dir }}"
       state: absent
