- name: Clone lab wiki
  git:
    repo: "{{ courseware_wiki_repo }}"
    dest: "{{ courseware_wiki_repo_dir }}"
    update: false

- name: Check whether wiki referrer policy patch is already applied
  command:
    argv:
      - git
      - apply
      - --reverse
      - --check
      - "{{ role_path }}/files/referrer-policy.patch"
  args:
    chdir: "{{ courseware_wiki_repo_dir }}"
  register: courseware_wiki_referrer_policy_patch
  changed_when: false
  failed_when: false

- name: Apply managed wiki referrer policy patch
  command:
    argv:
      - git
      - apply
      - "{{ role_path }}/files/referrer-policy.patch"
  args:
    chdir: "{{ courseware_wiki_repo_dir }}"
  when: courseware_wiki_referrer_policy_patch.rc != 0

- name: Install wiki dependencies with contained Node runtime
  command: npm install
  args:
    chdir: "{{ courseware_wiki_repo_dir }}"
    creates: "{{ courseware_wiki_repo_dir }}/node_modules/next/package.json"
  environment:
    PATH: "{{ courseware_node_runtime_bin_dir }}:{{ ansible_env.PATH }}"

- name: Render wiki runtime config
  template:
    src: courseware-runtime.json.j2
    dest: "{{ courseware_wiki_runtime_config_path }}"
    mode: "0644"

- name: Stat wiki build output
  stat:
    path: "{{ courseware_wiki_repo_dir }}/.next/BUILD_ID"
  register: courseware_wiki_build

- name: Build wiki for managed service startup
  command: npm run build
  args:
    chdir: "{{ courseware_wiki_repo_dir }}"
  environment:
    PATH: "{{ courseware_node_runtime_bin_dir }}:{{ ansible_env.PATH }}"
  when:
    - not courseware_wiki_build.stat.exists or courseware_wiki_referrer_policy_patch.rc != 0
