- name: Atualizar pacotes e instalar dependências básicas
  become: true
  apt:
    name:
      - curl
      - git
      - unzip
      - jq
      - gnupg
      - ca-certificates
    state: present
    update_cache: true

- name: Adicionar repositório NodeSource para Node.js 20
  become: true
  shell: curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
  args:
    executable: /bin/bash

- name: Instalar Node.js 20
  become: true
  apt:
    name: nodejs
    state: present
    update_cache: true

- name: Verificar versão do Node.js
  command: node -v
  register: node_version
  changed_when: false

- name: Verificar versão do npm
  command: npm -v
  register: npm_version
  changed_when: false
  
- name: Instalar Bitwarden CLI via npm
  become: true
  shell: npm install -g @bitwarden/cli@2025.11.0
  args:
    executable: /bin/bash

- name: Verificar instalação do Bitwarden CLI
  command: bw --version
  register: bw_version
  failed_when: bw_version.rc != 0

- name: Garantir logout do Bitwarden antes de configurar
  shell: bw logout
  ignore_errors: true

- name: Fazer login no Bitwarden
  shell: | 
    bw --version
    echo "config"
    echo "VAULTWARDEN_LINK: {{ VAULTWARDEN_LINK }}"
    bw config server {{ VAULTWARDEN_LINK }}
    echo $BW_CLIENTID
    echo $BW_CLIENTSECRET
    echo "login"
    bw login --apikey
  environment:
    BW_CLIENTID: "{{ BW_CLIENTID }}"
    BW_CLIENTSECRET: "{{ BW_CLIENTSECRET }}"
    VAULTWARDEN_LINK: "{{ VAULTWARDEN_LINK }}"
  args:
    executable: /bin/bash
  register: bw_login

- name: Desbloquear cofre e guardar sessão
  shell: bw unlock {{ bw_password }} --raw
  register: bw_session
  environment:
    BW_PASSWORD: "{{ BW_PASSWORD }}"

- name: Exportar sessão para ambiente local
  shell: echo "export BW_SESSION={{ bw_session.stdout }}" >> /etc/profile.d/bw-session.sh
  become: true