- name: Copy file with owner and permissions
  hosts: "{{ all | default('all', true) }}"
  become: true
  gather_facts: true
  vars:
    permissions: "0755"
    owner: "root"
    setupfiles_root_dir: "{{ lookup('env', 'SETUPFILES_ROOT_DIR') }}"
    build_dir: "{{ lookup('env', 'BUILD_DIR') }}"
    # WARNING: Files in this list will be REMOVED
    cleanup:
      - "/usr/local/setupfiles/somethingtodelete.txt"
      - "/etc/profile.d/sf00-vars.sh"
      # - "/etc/profile.d/init.sh"
      # - "/usr/local/share/scripts/scripts"
      # - "/usr/local/bin/bin"
      - "/usr/local/share/scripts"
      - "/usr/local/share/services"
      - "/usr/local/setupfiles/bin/update"
      - "/usr/local/setupfiles/bin/fastfetch"
      - "/usr/local/setupfiles/bin/flashfetch"
    # bins_cleanup:
    #   - "argtest"
    #   - "cronlist"
    #   - "dc"
    #   - "deploy"
    #   - "deployment_info"
    #   - "echon"
    #   - "empty"
    #   - "genhostname"
    #   - "netools"
    #   - "netrefresh"
    #   - "nopasswd"
    #   - "os"
    #   - "prompt"
    #   - "randomhost"
    #   - "rexit"
    #   - "runas"
    #   - "ser"
    #   - "sethostname"
    #   - "setowner"
    #   - "setperm"
    #   - "sf"
    #   - "sf-run"
    #   - "ssh-init"
    #   - "update"
    #   - "upt"
    #   - "writelog"
    deleted_dir: "{{ setupfiles_root_dir }}/.deleted"
  tasks:

  # NOTE: Ensure `deleted_dir` exists
  - name: Ensure `deleted_dir` exists
    ansible.builtin.file:
      path: "{{ deleted_dir }}"
      state: directory

    
  # # NOTE: Copy over everything inside /usr/local/bin to /usr/local/bin/.deleted
  # - name: Copying files to deleted dir
  #   ansible.builtin.copy:
  #     src: "/usr/local/bin/"
  #     dest: "{{ deleted_dir }}/bin/"

  # # Delete everything inside /usr/local/bin
  # - name: Remove files
  #   ansible.builtin.file:
  #     path: "/usr/local/bin/"
  #     state: absent

  # NOTE: Copy "cleanup" files to deleted dir (ignore if file doesn't exist)
  - name: Copying files to deleted dir
    ansible.builtin.copy:
      src: "{{ item }}"
      dest: "{{ deleted_dir }}/{{ item | basename }}"
    with_items: "{{ cleanup }}"
    ignore_errors: true
    # when: item is not none and (item is file or item is dir)
    
  # NOTE: Remove files (ignore if file doesn't exist)
  - name: Remove files
    ansible.builtin.file:
      path: "{{ item }}"
      state: absent
    with_items: "{{ cleanup }}"
    ignore_errors: true
    # when: item is not none and (item is file or item is dir)

  # - name: Remove files in /usr/local/bin
  #   ansible.builtin.file:
  #     path: "/usr/local/bin/{{ item }}"
  #     state: absent
  #   with_items: "{{ bins_cleanup }}"
  #   ignore_errors: true