# Lokole PDF (User's Guide) gets copied for offline use (http://box/info) here:
# https://github.com/iiab/iiab/blob/master/roles/www_base/templates/iiab-refresh-wiki-docs.sh#L51-L52


- name: Record (initial) disk space used
  shell: df -B1 --output=used / | tail -1
  register: df1


# 1. TEST IF Node.js ALEADY INSTALLED & IF SO WARN IT'LL BE REPLACED

# 2019-02-03: BELOW TESTS IF 'nodejs' VERSION IS ALREADY INSTALLED:
# IF SO & THIS DOESN'T MATCH nodejs_version AS SET IN defaults_vars.yml
# AND/OR local_vars.yml, INSTALL HALTS WITH AN EXPLANATION (PR #1447)

# 2019-07-04: FOR A SOMEWHAT MORE MODERN "VERSION DETECTOR" SEE:
# github.com/iiab/iiab/blob/master/roles/nextcloud/tasks/install.yml#L1-L40

- name: Try to run 'node -v' to get Node.js version
  # 'node -v' doesn't work with older versions e.g. Ubuntu 16.04's Node.js 4.2.6
  # 'nodejs -v' doesn't work with newer versions e.g. Node.js 16.x
  # Each below convert v10.15.1 to 10.x, but this is safest:
  shell: node -v | sed 's/^[^0-9]*\([0-9][0-9]*\).*$/\1.x/'
  # Capturing Groups & Backreferences -> GNU BRE: (Basic Regular Expression)
  # https://www.regular-expressions.info/refcapture.html
  # https://www.regular-expressions.info/gnu.html#bre
  #shell: node -v | sed 's/[^0-9]*//; s/[^0-9].*/.x/'
  #shell: node -v | sed 's/[^[:digit:]]*//; s/[^[:digit:]].*/.x/'
  #shell: node -v | sed 's/^[vV]//' | sed 's/\..*/.x/'
  register: nodejs_version_installed

# When nodejs is NOT installed:
# nodejs_version_installed.rc == 0    # COUNTERINTUITIVE BUT 'echo $?' CONFIRMS (pipe zeros out error) -- thankfully STDERR msg from left side of pipe preserved below.
# nodejs_version_installed.stdout == ""
# nodejs_version_installed.stderr == "/bin/sh: 1: nodejs: not found"
# BOTH ABOVE (incl non-null stderr) [were] USED BELOW to confirm install is nec!

#- name: "ENFORCE PRECONDITION: Stop installing (intentionally fail) IF an installed 'nodejs' version isn't {{ nodejs_version }}"
#  fail:
#    msg: >
#      PLEASE REMOVE 'nodejs' VERSION {{ nodejs_version_installed.stdout }} AS
#      IT DOES NOT MATCH THE REQUIRED nodejs_version: {{ nodejs_version }} --
#      as set in /opt/iiab/iiab/vars/default_vars.yml and/or
#      /etc/iiab/local_vars.yml -- then re-run this IIAB installer.
#  when: nodejs_version_installed is defined and nodejs_version_installed.stdout != nodejs_version and nodejs_version_installed.stderr == ""

# 2021-08-04: Regardless, nodesource.com (below) overwrites /etc/apt/sources.list.d/nodesource.list
# Forces < 16.x or > 16.x to be removed, ignored if file is absent
#- name: Remove /etc/apt/sources.list.d/nodesource.list if nodejs_version_installed.stdout is not {{ nodejs_version }}
#  file:
#    state: absent
#    path: /etc/apt/sources.list.d/nodesource.list
#  when: nodejs_version_installed is defined and nodejs_version_installed.stdout != nodejs_version
#  when: nodejs_version_installed is defined and nodejs_version_installed.stdout != nodejs_version and nodejs_version_installed.stdout != ""

- name: LOUD WARNING if Node.js will be replaced -- BRUTAL but helps OS's / distros with older Node.js
  #debug:    # GREEN
  fail:      # FORCE IT RED THIS ONCE!
    msg: "WARNING: YOUR Node.js {{ nodejs_version_installed.stdout }} WILL BE WIPED AND REPLACED"
  when: nodejs_version_installed.stderr == ""    # and nodejs_version_installed.stdout == nodejs_version
  ignore_errors: yes

# 2022-10-22: Above 2 stanzas could be removed (tho informational value remains)

- name: ASK apt TO REMOVE ANY PRE-EXISTING Node.js AND npm
  package:
    name:
      - nodejs
      - npm
    state: absent


# 2. INSTALL Node.js AND npm USING nodesource.com (OR OS's apt IF THAT FAILS!)

# 2019-02-12: Should not be nec, as stanza below it should overwrite
# /etc/apt/sources.list.d/nodesource.list regardless!
#
#- name: Clear prior /etc/apt/sources.list.d/nodesource.list (permitting Node.js downgrade if nec)
#  file:
#    path: /etc/apt/sources.list.d/nodesource.list
#    state: absent
#  when: internet_available and is_debuntu

# MANUAL NODESOURCE INSTALL *WORKS* EVEN PRIOR TO OFFICIAL DISTRO SUPPORT AT:
# https://github.com/nodesource/distributions#deb
# https://deb.nodesource.com/node_18.x/dists/
#
# 1) e.g. Ubuntu 22.04:
# wget https://deb.nodesource.com/node_18.x/pool/main/n/nodejs/nodejs_18.0.0-deb-1nodesource1_amd64.deb
# apt install ./nodejs_18.0.0-deb-1nodesource1_amd64.deb    # SMARTER + CLEANER THAN: dpkg -i nodejs_18...
# echo 'nodejs_installed: True' >> /etc/iiab/iiab_state.yml
#
# 2) e.g. Ubuntu 22.10:
# wget https://deb.nodesource.com/node_18.x/pool/main/n/nodejs/nodejs_18.11.0-deb-1nodesource1_amd64.deb
# apt install ./nodejs_18.11.0-deb-1nodesource1_amd64.deb    # SMARTER + CLEANER THAN: dpkg -i nodejs_18...
# echo 'nodejs_installed: True' >> /etc/iiab/iiab_state.yml

- name: Try NEW (since August 2023) approach setting up /etc/apt/keyrings/nodesource.gpg and /etc/apt/sources.list.d/nodesource.list -- per https://github.com/nodesource/distributions#installation-instructions
  shell: |
    mkdir -p /etc/apt/keyrings
    rm -f /etc/apt/keyrings/nodesource.gpg
    curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
    echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_{{ nodejs_version }} nodistro main" > /etc/apt/sources.list.d/nodesource.list
  register: curl_nodesource
  ignore_errors: yes

# 2023-09-06: OBSOLETE as nodesource.com no longer supports https://deb.nodesource.com/node_{{ nodejs_version }}/dists/
# - name: Try 'curl -fsSL https://deb.nodesource.com/setup_{{ nodejs_version }} | bash -' to overwrite /etc/apt/sources.list.d/nodesource.list
#   shell: curl -fsSL https://deb.nodesource.com/setup_{{ nodejs_version }} | bash -
#   register: curl_nodesource
#   ignore_errors: yes
#   #args:
#   #  warn: no
#   #  creates: /etc/apt/sources.list.d/nodesource.list

- name: Remove /etc/apt/sources.list.d/nodesource.list if above failed
  file:
    path: /etc/apt/sources.list.d/nodesource.list
    state: absent
  when: curl_nodesource.failed

- name: Install Node.js -- also includes /usr/bin/npm if nodesource.list installed above
  apt:
    #name: nodejs={{ nodejs_version }}
    name: nodejs
    state: latest    # Equivalent to 'state: present' ?
    update_cache: yes

# Also run 'npm install -g npm' later, if you truly want the LATEST!
- name: Also install latest npm (OS's) if nodesource failed to install above -- i.e. if OS not yet supported by https://github.com/nodesource/distributions
  package:
    name: npm
    state: latest    # Equivalent to 'state: present' ?
  when: curl_nodesource.failed

# NEED BLEEDING EDGE? Then Also Run: npm install -g npm@latest

# 2018-07-14: BOTH STEPS ABOVE TAKE TIME, but Raspbian (apt offers npm
# 1.4.21) & Debian 9 (apt offers no npm!) STILL NEED the above
# nodesource.com approach to get a version of npm that works with Sugarizer:
# https://github.com/iiab/iiab/issues/798#issuecomment-404324530
#
# MORE POSITIVELY: this nodesource.com approach (brings in npm 5.6.0 with
# nodejs 8.11.3 for now, to any OS) would also work on Ubuntu 18.04, and
# might even bring about a sane consistency across mainline OS's?
#
# BUT FOR NOW: Ubuntu 18.04's apt (approach below) brings in npm 3.5.2,
# which appears suffic "SO FAR"?  18.04's nodejs 8.10.0 is more reassuring!
#
# CRAZY IDEA: most versions of npm can upgrade themselves to the latest
# (6.2.0 for now) using "npm install -g npm" or "npm install -g npm@latest",
# if that helps us in future, e.g. TK's memory issue etc?  If so, be CAREFUL
# this puts npm in /usr/local/bin on Ubuntu 18.04 -- unlike Ubuntu 16.04 and
# Raspbian where it upgrades /usr/bin/npm in place:
# https://askubuntu.com/questions/1036278/npm-is-incorrect-version-on-latest-ubuntu-18-04-installation

# 2019-02-03: OLD WAY (PRIOR TO 2019) BELOW.  Since then, @m-anish helped
# us standardize on the above nodesource.com approach i.e.
# https://github.com/nodesource/distributions#debinstall ...across all
# distros (so nodejs & npm always findable in /usr/bin, for Node-RED etc)

# - name: Install packages nodejs {{ nodejs_version }} and npm (debuntu distros AFTER 2017, or other distros)
#   package:
#     name:
#       - nodejs={{ nodejs_version }}    # Nec to change above from 'package:' to 'apt:' ?
#       - npm
#     state: latest
#   when: internet_available and not (is_debian_8 or is_debian_9 or is_ubuntu_16 or is_ubuntu_17)

# 2019-01-16: fyi Node.js 10.x became "LTS" on 2018-10-30 but distros are
# holding back for now: certainly Ubuntu 18.04 and even Debian 10/Buster
# ("testing" branch) both install Node.js 8.x (instead of 10.x).  While the
# more bleeding-edge Debian Sid ("unstable" branch) does install Node.js 10.x
#
# This May Change: thanks all for running "apt -a list nodejs" on Buster's
# daily builds @ www.debian.org/devel/debian-installer/ and Disco Dingo (Ubuntu
# 19.04) https://launchpad.net/ubuntu/+source/nodejs to keep us informed!

# 2019-03-29: Debian 10 Buster & Ubuntu 19.04 pre-releases made the jump
# thankfully; currently both offer Node.js 10.15.2


# 3. RECORD Node.js AS INSTALLED

- name: Record (final) disk space used
  shell: df -B1 --output=used / | tail -1
  register: df2

- name: Add 'nodejs_disk_usage = {{ df2.stdout|int - df1.stdout|int }}' to {{ iiab_ini_file }}
  ini_file:
    path: "{{ iiab_ini_file }}"    # /etc/iiab/iiab.ini
    section: nodejs
    option: nodejs_disk_usage
    value: "{{ df2.stdout|int - df1.stdout|int }}"

- name: "Set 'nodejs_installed: True'"
  set_fact:
    nodejs_installed: True

- name: "Add 'nodejs_installed: True' to {{ iiab_state_file }}"
  lineinfile:
    path: "{{ iiab_state_file }}"    # /etc/iiab/iiab_state.yml
    regexp: '^nodejs_installed'
    line: 'nodejs_installed: True'