---
#--------------------------------------------------------------#
# INSIGHT - Observability Workbench Deployment
#--------------------------------------------------------------#

- name: install nodejs and build tools
  tags: insight_pkg
  apt:
    name:
      - nodejs
      - npm
      - build-essential
      - make
    state: present
    default_release: trixie
    update_cache: yes

- name: create workbench directory
  tags: insight_dir
  file:
    path: "{{ workbench_dir }}"
    state: directory
    owner: "{{ workbench_user }}"
    group: "{{ workbench_group }}"
    mode: '0755'

- name: sync workbench source code
  tags: insight_sync
  synchronize:
    src: "{{ playbook_dir }}/workbench/"
    dest: "{{ workbench_dir }}/"
    delete: yes
    recursive: yes
    rsync_opts:
      - "--exclude=.next"
      - "--exclude=node_modules"
      - "--exclude=.git"

- name: install npm dependencies
  tags: insight_build
  when: workbench_build|bool
  shell: npm install --legacy-peer-deps --no-audit --prefer-offline
  args:
    chdir: "{{ workbench_dir }}"
  environment: "{{ (proxy_env | default({})) | combine({'NODE_OPTIONS': '--max-old-space-size=1024'}) }}"
  async: 1800
  poll: 10

- name: build nextjs workbench
  tags: insight_build
  when: workbench_build|bool
  shell: npm run build
  args:
    chdir: "{{ workbench_dir }}"
    executable: /bin/bash
  environment: "{{ (proxy_env | default({})) | combine({'PATH': '/usr/local/bin:/usr/bin:/bin', 'NODE_ENV': 'production', 'NODE_OPTIONS': '--max-old-space-size=1536'}) }}"
  async: 1800
  poll: 10

- name: render insight systemd service
  tags: insight_config
  template:
    src: insight.service.j2
    dest: /etc/systemd/system/insight.service
    owner: root
    group: root
    mode: '0644'

- name: launch insight service
  tags: insight_launch
  systemd:
    name: insight
    state: restarted
    enabled: yes
    daemon_reload: yes

- name: wait for insight workbench
  tags: insight_launch
  wait_for:
    host: 127.0.0.1
    port: "{{ workbench_port }}"
    state: started
    timeout: 60

...
