# code: language=ansible
---
- name: Install AstroNvim
  hosts: localhost
  connection: local
  gather_facts: true

  vars:
    theme: "dracula-nvim"
    colorscheme: "dracula"

  tasks:
    - name: Add unstable repository from PPA and install on Debian or Ubuntu
      ansible.builtin.apt_repository:
        repo: ppa:neovim-ppa/unstable
        state: present
      when: ansible_pkg_mgr == "apt"

    - name: Update package cache
      ansible.builtin.package:
        update_cache: true
        # cache_valid_time: 3600

    - name: Install NeoVim
      become: true
      ansible.builtin.package:
        name:
          - neovim

    - name: Install NodeJS on ArchLinux
      become: true
      ansible.builtin.package:
        name:
          - nodejs-lts-iron
          - npm
      when: ansible_pkg_mgr == "pacman"

    - name: Install NodeJS on Debian or Ubuntu
      become: true
      ansible.builtin.package:
        name:
          - nodejs
          - npm
      when: ansible_pkg_mgr == "apt"

    - name: Install NodeJS on MacOS
      become: true
      ansible.builtin.package:
        name:
          - node
      when: ansible_facts['os_family'] == 'Darwin'

    - name: Clone a Git repository
      ansible.builtin.git:
        repo: '{{ item.from }}'
        dest: '{{ item.to }}'
        clone: true
        depth: 1
        recursive: true
        version: '{{ item.version }}'
        accept_hostkey: true
        force: true
        update: true
      with_items:
        - { from: 'https://github.com/AstroNvim/template', to: '~/.config/nvim', version: 'main' }

    - name: Replace AstroNvim Setting
      ansible.builtin.replace:
        path: "{{ item }}"
        regexp: '^(if true then return {} end.*)$'
        replace: ''
      with_fileglob:
        - "~/.config/nvim/lua/community.lua"
        - "~/.config/nvim/lua/plugins/*.lua"
      loop_control:
        loop_var: item
      register: result

    - name: Insert lines in community.lua
      ansible.builtin.blockinfile:
        path: "~/.config/nvim/lua/community.lua"
        block: |
            { import = "astrocommunity.colorscheme.{{ theme }}" },
            { import = "astrocommunity.pack.python" },
        insertbefore: '^}'
        marker: "  -- {mark} ANSIBLE MANAGED BLOCK"

    - name: Change colorscheme in astroui.lua
      ansible.builtin.replace:
        path: ~/.config/nvim/lua/plugins/astroui.lua
        regexp: 'colorscheme = "astrodark",'
        replace: 'colorscheme = "{{ colorscheme }}",'

    - name: Install AstroNvim
      ansible.builtin.shell: |
        nvim --headless -c 'quitall'
      register: result
