---
- name: Add static dotfiles
  copy:
    src: "{{ item }}"
    dest: "~/{{ item }}"
    owner: "{{ user.username }}"
    group: "{{ user.group | default(omit) }}"
    mode: 0600
  loop:
    - .localrc
    - .zshrc

- name: Ensure VAGRANT_CLOUD_TOKEN is included in .localrc, if set
  lineinfile:
    path: ~/.localrc
    regex: "export VAGRANT_CLOUD_TOKEN"
    line: "export VAGRANT_CLOUD_TOKEN={{ user.vagrant_cloud_token }}"
  when: user.vagrant_cloud_token is defined

- name: Add dynamic dotfiles
  template:
    src: "{{ item }}.j2"
    dest: "~/{{ item }}"
    owner: "{{ user.username }}"
    group: "{{ user.group | default(omit) }}"
    mode: 0600
  loop:
    - .gitconfig
    - .netrc
    - .npmrc
    - .tinypng

- name: Determine whether the user's .bashrc file is present in the home directory
  stat:
    path: ~/.bashrc
  register: bashrc

- name: Ensure .bashrc exists in user's home directory
  file:
    mode: 0600
    path: ~/.bashrc
    state: touch
  when: not bashrc.stat.exists

- name: Ensure .localrc is sourced in .bashrc
  lineinfile:
    path: ~/.bashrc
    regex: "^source ~\/.localrc$"
    line: source ~/.localrc

- name: Set .bashrc PATH variable
  lineinfile:
    path: ~/.bashrc
    regex: "# PATH modified by Ansible"
    line: "export PATH=$PATH:~/.local/bin # PATH modified by Ansible"

- name: Attempt to run starship and register the response
  shell: type starship > /dev/null
  changed_when: false
  register: has_starship
  failed_when: has_starship.rc != 0 and not (has_starship.rc == 1  and 'not found' in has_starship.stderr)

- name: Remove starship references if starship command is unavailable
  lineinfile:
    path: "~/{{ item.file }}"
    regex: "starship init {{ item.exe }}"
    line: "#eval '$(starship init {{ item.exe }})'"
  loop:
    - file: .localrc
      exe: bash
    - file: .zshrc
      exe: zsh
  when: "'not found' in has_starship.stderr"
