- name: Create docker network websoft9
  shell: docker network create websoft9
  failed_when: False

- name: Git Clone app docker repository and change public IP
  block:
    - name: Delete {{app}} dir for Second installation
      shell: rm -rf {{installpath}}/{{app}} {{installpath}}/library
      
    - name: Clone docker-library in Websoft9
      shell: |
        wget -N https://websoft9.github.io/StackHub/scripts/githubclone.sh
        bash githubclone.sh websoft9 docker-library
        mv docker-library library
        cp -r  library  "{{installpath}}"
        cp -r  "{{installpath}}/library/apps/{{app}}"  "{{installpath}}"
      async: 1800
      
    - name: Check port file exists
      stat:
        path: /tmp/port.txt
      register: port
    
    - name: Input {{appname}} port
      shell: |
        cat "{{installpath}}/library/apps/{{appname}}/.env" |grep APP_HTTP_PORT >> /tmp/port.txt      
        sed -i "s/APP_HTTP_PORT=//g" /tmp/port.txt
      when: port.stat.exists == False
        
    - name: Check APP_URL_REPLACE exists
      shell: |
        cat "{{installpath}}/{{app}}/.env" |grep APP_URL_REPLACE=true
      register: http_url_exists
      failed_when: false

    - name: Change Public IP for http_url if APP_URL_REPLACE=true
      shell: |
         public_ip=`bash /credentials/get_ip.sh`
         urlstr=`grep  "APP_URL=" /data/apps/{{app}}/.env |cut -d":" -f1`
         sudo sed -i "s/$urlstr/APP_URL=$public_ip/g" /data/apps/{{app}}/.env
      when: http_url_exists.stdout != ""
      
- name: Excute Preparation if have pre.yml
  block:
    - name: Check if pre.yml exists
      stat:
        path: ./roles/{{app}}/tasks/pre.yml
      register: pre_exists
      delegate_to: 127.0.0.1
      
    - name: Excute pre.yml
      include_tasks: roles/{{app}}/tasks/pre.yml
      when: pre_exists.stat.exists == True

- name: Copy auto_addport.sh
  copy: src=../scripts/auto_addport.sh  dest=/tmp/auto_addport.sh
  
- name: If this port in use, add a new port for this app 
  shell: |
    bash /tmp/auto_addport.sh "{{app}}"
  when: app != appname
        
- block:
  - name: Docker compose up
    shell: |
      docker compose up -d
      sleep 30
    args:
      chdir: "{{installpath}}/{{app}}"

  - name: Recursively create directory for {{app}}
    file:
      path: "{{ item }}"
      state: directory
      recurse: yes
    with_items:
      - "{{installpath}}/{{app}}/data"

  - name: Add softlink of all volumes for app root directory
    block:
    - name: Get volumes name
      shell: docker compose config --volumes
      register: volume_names
      args:
        chdir: "{{installpath}}/{{app}}"

    - name: Create softlink of volumes
      file:
        src: "/var/lib/docker/volumes/{{app}}_{{item}}/_data"
        dest: "{{installpath}}/{{app}}/data/{{item}}"
        state: link
        force: yes
      loop: "{{volume_names.stdout_lines}}"
