---
- name: "Install Rasa X"
  hosts: "localhost"
  become: True
  vars:
    RASA_HOME: "{{ lookup('env','RASA_HOME')|default('/etc/rasa', true) }}"
    terms_confirmed: False
  roles:
    - role: angstwad.docker_ubuntu
      when: ansible_testing is not defined

  tasks:
  - name: Status of Rasa Enterprise license file
    stat:
      path: rasa-x-ee-license.yml
    register: rasa_x_license_file

  - name: Check if a license exists
    debug:
      msg: "There is no Rasa Enterprise license file. We will install Rasa X (Community Edition)."
    when: rasa_x_license_file.stat.exists == False

  - name: Load configuration file of the customer (includes e.g. the license)
    include_vars:
      file: rasa-x-ee-license.yml
      name: rasax
    when: rasa_x_license_file.stat.exists

  - name: Create Rasa X root directory
    file:
      path: "{{ RASA_HOME }}"
      state: directory

  - name: Create Rasa X log directory
    file:
      path: "{{ RASA_HOME }}/logs"
      state: directory
      mode: 0770
      group: root

  - name: Create Rasa X scripts directory
    file:
      path: "{{ RASA_HOME }}/scripts"
      state: directory

  - name: Create Rasa X mongo migration directory
    file:
      path: "{{ RASA_HOME }}/scripts/mongo_migration"
      state: directory

  - name: Create the directory to store terms accept file
    file:
      path: "{{ RASA_HOME }}/terms"
      state: directory
      mode: 0770
      group: root

  - name: Create the directory for the database persistence
    file:
      path: "{{ RASA_HOME }}/db"
      state: directory
      mode: 0750
      owner: "1001"
      group: root

  - name: Create the directory to store the models
    file:
      path: "{{ RASA_HOME }}/models"
      state: directory
      mode: 0770
      group: root

  - name: Create the directory for the authentication
    file:
      path: "{{ RASA_HOME }}/auth"
      state: directory
      mode: 0770
      group: root

  - name: Create the directory for the credentials
    file:
      path: "{{ RASA_HOME }}/credentials"
      state: directory
      mode: 0770
      group: root

  - name: Create the directory to store the certificate files
    file:
      path: "{{ RASA_HOME }}/certs"
      state: directory
      mode: 0770
      group: root

  - name: Prompt for Rasa Enterprise terms and conditions
    pause:
      prompt: "Do you accept the Rasa Enterprise terms and conditions? Please read them at https://storage.googleapis.com/rasa-x-releases/rasa_x_ee_license_agreement.pdf. Answer with 'YES' or simply press return to agree."
    when: not (terms_confirmed | bool) and rasa_x_license_file.stat.exists
    register: user_terms_response

  - name: Store user input value
    set_fact: terms_confirmed="{{user_terms_response.user_input or True}}"
    when: user_terms_response.user_input is defined

  - name: Prompt for Rasa X (Community Edition) terms and conditions
    pause:
      prompt: "Do you accept the Rasa X terms and conditions? Please read them at https://storage.googleapis.com/rasa-x-releases/rasa_x_ce_license_agreement.pdf. Answer with 'YES' or simply press return to agree."
    when: not (terms_confirmed | bool) and not rasa_x_license_file.stat.exists
    register: user_terms_response

  - name: Store user input value
    set_fact: terms_confirmed="{{user_terms_response.user_input or True}}"
    when: user_terms_response.user_input is defined

  - name: Check terms and conditions were accepted
    assert:
      that:
      -  terms_confirmed | bool # `YES` is handled as `true` in YAML
      msg: "You need to accept the terms and conditions to run Rasa X. Please re-run the installation script and accept the terms"

  - name: write agree file
    shell: echo "${USER} $(date)" > {{ RASA_HOME }}/terms/agree.txt
    when: terms_confirmed | bool

  - name: Adapt permissions of agreement file
    file:
      path: "{{ RASA_HOME }}/terms/agree.txt"
      mode: 770
      group: root

  - name: stat user credentials
    stat: path=credentials
    register: user_credentials_dir

  - name: backwards compatible credentials
    command: mv credentials {{ RASA_HOME }}/credentials
    when: user_credentials_dir.stat.exists

  - name: Status of Rasa X credentials folder
    stat:
      path: "{{ RASA_HOME }}/credentials"
    register: rasa_x_credentials

  - name: Status of Rasa X env file
    stat:
      path: "{{ RASA_HOME }}/.env"
    register: rasa_x_env

  - name: Ensure we do not overwrite the env if we do not have the credentials
    assert:
      that:
      - "not (rasa_x_env.stat.exists and not rasa_x_credentials.stat.exists)"
      msg: "There is a Rasa X env ({{ RASA_HOME }}/.env) but no folder containing the original credentials. To avoid overwriting the existing credentials in .env we ABORT. "

  - name: Create the environment for the docker compose runner
    copy:
      content: |
        PASSWORD_SALT={{ lookup('password', '{{ RASA_HOME }}/credentials/password_salt length=15') }}
        RASA_X_VERSION=0.25.2
        RASA_VERSION=1.7.0
        RASA_X_DEMO_VERSION=0.25.0
      dest: "{{ RASA_HOME }}/.env"
    when: rasa_x_env.stat.exists == False

  - name: Update Rasa X version in `.env` file if `.env` file already existed
    lineinfile:
      path: "{{ RASA_HOME }}/.env"
      regexp: "RASA_X_VERSION=.*"
      line: "RASA_X_VERSION=0.25.2"
    when: rasa_x_env.stat.exists

  - name: Update Rasa version in `.env` file if `.env` file already existed
    lineinfile:
      path: "{{ RASA_HOME }}/.env"
      regexp: "RASA_VERSION=.*"
      line: "RASA_VERSION=1.7.0"
    when: rasa_x_env.stat.exists

  - name: Update RASA X demo version in `.env` file if `.env` file already existed
    lineinfile:
      path: "{{ RASA_HOME }}/.env"
      regexp: "RASA_X_DEMO_VERSION=.*"
      line: "RASA_X_DEMO_VERSION=0.25.0"
    when: rasa_x_env.stat.exists

  - name: Read the the content of the .env file
    shell: cat "{{ RASA_HOME }}/.env"
    register: env_content

  - name: Status of deployment environments file
    stat:
      path: "{{ RASA_HOME }}/environments.yml"
    register: environments_file

  - name: Create deployment environments file if not present
    copy:
      content: |
        rasa:
          production:
            url: ${RASA_PRODUCTION_HOST}
            token: ${RASA_TOKEN}
          worker:
            url: ${RASA_WORKER_HOST}
            token: ${RASA_TOKEN}

      dest: "{{ RASA_HOME }}/environments.yml"
      mode: 0770
      group: root
    when: environments_file.stat.exists == False

  - name: Status of Redis credentials file
    stat:
      path: "{{ RASA_HOME }}/credentials/redis"
    register: redis_credentials

  - name: Create Redis credentials if not present
    lineinfile:
      path: "{{ RASA_HOME }}/.env"
      line: "REDIS_PASSWORD={{ lookup('password', '{{ RASA_HOME }}/credentials/redis length=15') }}"
    when: redis_credentials.stat.exists == False

  - name: Status of RabbitMQ credentials file
    stat:
      path: "{{ RASA_HOME }}/credentials/rabbit"
    register: rabbitmq_credentials

  - name: Create RabbitMQ credentials if not present
    lineinfile:
      path: "{{ RASA_HOME }}/.env"
      line: "RABBITMQ_PASSWORD={{ lookup('password', '{{ RASA_HOME }}/credentials/rabbit length=15') }}"
    when: rabbitmq_credentials.stat.exists == False

  - name: Status of RASA_X_TOKEN credentials file
    stat:
      path: "{{ RASA_HOME }}/credentials/rasa_x_token"
    register: rasa_x_token

  - name: Create RASA_X_TOKEN credentials if not present
    lineinfile:
      path: "{{ RASA_HOME }}/.env"
      line: "RASA_X_TOKEN={{ lookup('password', '{{ RASA_HOME }}/credentials/rasa_x_token chars=ascii_letters,digits length=15') }}"
    when: rasa_x_token.stat.exists == False

  - name: Status of JWT_SECRET credentials file
    stat:
      path: "{{ RASA_HOME }}/credentials/jwt_secret"
    register: jwt_secret

  - name: Create JWT_SECRET credentials if not present
    lineinfile:
      path: "{{ RASA_HOME }}/.env"
      line: "JWT_SECRET={{ lookup('password', '{{ RASA_HOME }}/credentials/jwt_secret chars=ascii_letters,digits length=25') }}"
    when: jwt_secret.stat.exists == False

  - name: Status of RASA_TOKEN credentials file
    stat:
      path: "{{ RASA_HOME }}/credentials/rasa_token"
    register: rasa_token

  - name: Create RASA_TOKEN if not present
    lineinfile:
      path: "{{ RASA_HOME }}/.env"
      line: "RASA_TOKEN={{ lookup('password', '{{ RASA_HOME }}/credentials/rasa_token chars=ascii_letters,digits length=15') }}"
    when: rasa_token.stat.exists == False

  - name: Status of db password credentials file
    stat:
      path: "{{ RASA_HOME }}/credentials/db"
    register: db_password

  - name: Create DB_PASSWORD if not present
    lineinfile:
      path: "{{ RASA_HOME }}/.env"
      line: "DB_PASSWORD={{ lookup('password', '{{ RASA_HOME }}/credentials/db length=15 chars=ascii_letters,digits') }}"
    when: db_password.stat.exists == False

  - name: Status of channel credentials file
    stat:
      path: "{{ RASA_HOME }}/credentials.yml"
    register: credentials_file

  - name: Create the environment for the docker compose runner
    copy:
      content: |
        rasa:
          url: ${RASA_X_HOST}/api
      dest: "{{ RASA_HOME }}/credentials.yml"
      mode: 0770
      group: root
    when: credentials_file.stat.exists == False

  - name: Status of the Rasa endpoint configuration file
    stat:
      path: "{{ RASA_HOME }}/endpoints.yml"
    register: stack_endpoints_file

  - name: Create the endpoints configuration file for Rasa
    copy:
      content: |
        models:
          url: ${RASA_MODEL_SERVER}
          token: ${RASA_X_TOKEN}
          wait_time_between_pulls: ${RASA_MODEL_PULL_INTERVAL}
        tracker_store:
          type: sql
          dialect: "postgresql"
          url: ${DB_HOST}
          port: ${DB_PORT}
          username: ${DB_USER}
          password: ${DB_PASSWORD}
          db: ${DB_DATABASE}
          login_db: ${DB_LOGIN_DB}
        lock_store:
          type: "redis"
          url: ${REDIS_HOST}
          port: ${REDIS_PORT}
          password: ${REDIS_PASSWORD}
          db: ${REDIS_DB}
        event_broker:
          type: "pika"
          url: ${RABBITMQ_HOST}
          username: ${RABBITMQ_USERNAME}
          password: ${RABBITMQ_PASSWORD}
          queue: ${RABBITMQ_QUEUE}
        action_endpoint:
          url: ${RASA_USER_APP}/webhook
          token:  ""
      dest: "{{ RASA_HOME }}/endpoints.yml"
      mode: 0770
      group: root
    when: stack_endpoints_file.stat.exists == False

  - name: Retrieve docker compose to run Rasa Enterprise
    get_url:
      url: https://storage.googleapis.com/rasa-x-releases/0.25.2/docker-compose.ee.yml
      dest: "{{ RASA_HOME }}/docker-compose.yml"
      mode: 0766
      force: yes
    when: (rasa_x_license_file.stat.exists and ansible_testing is not defined)

  - name: Retrieve docker compose to run Rasa X (Community Edition)
    get_url:
      url: https://storage.googleapis.com/rasa-x-releases/0.25.2/docker-compose.ce.yml
      dest: "{{ RASA_HOME }}/docker-compose.yml"
      mode: 0766
      force: yes
    when: (rasa_x_license_file.stat.exists == False and ansible_testing is not defined)

  - name: Retrieve the Rasa X commands file
    get_url:
      url: https://storage.googleapis.com/rasa-x-releases/0.25.2/rasa_x_commands.py
      dest: "{{ RASA_HOME }}/rasa_x_commands.py"
      mode: 0766
      force: yes
    when: ansible_testing is not defined

  - name: Dump gcr license to separate file
    copy:
      content: "{{rasax.docker_registry_license | from_json | to_nice_json}}"
      dest: "{{ RASA_HOME }}/gcr-auth.json"
    when: rasa_x_license_file.stat.exists

  - name: Log in to google cloud registry (gcr)
    shell: "docker login -u _json_key -p {{rasax.docker_registry_license|quote}} https://gcr.io"
    when: rasa_x_license_file.stat.exists

  - name: Retrieve the Rasa X mongo to sql migration files
    get_url:
      url: https://storage.googleapis.com/rasa-x-releases/0.25.2/scripts/mongo_migration/docker-compose.yml
      dest: "{{ RASA_HOME }}/scripts/mongo_migration/docker-compose.yml"
      mode: 0766
      force: yes
    when: ansible_testing is not defined

  - name: Status of the Rasa Migration script .env file
    stat:
      path: "{{ RASA_HOME }}/scripts/mongo_migration/.env"
    register: mongo_migration_env_file

  - name: Create a symbolic link to the root .env file in the migrations
    file:
      src: "{{ RASA_HOME }}/.env"
      dest: "{{ RASA_HOME }}/scripts/mongo_migration/.env"
      state: link
    when: mongo_migration_env_file.stat.exists == False
