- name: Create directories
  file:
    name: "{{ item }}"
    state: directory
    mode: 0755
    owner: root
    group: wheel
  loop:
    - /usr/local/etc/pkg
    - /usr/local/etc/pkg/repos

- name: Install packages
  package:
    name:
      - pkg-provides
    state: present

- name: Install Configuration
  copy:
    src: "files/{{ item.src }}"
    dest: "{{ item.dest }}"
    mode: 0644
    owner: root
    group: wheel
  loop:
    - src: pkg.conf
      dest: /usr/local/etc/pkg.conf

- name: Install Configuration
  when: custom_repo is not defined
  register: changed_config
  copy:
    src: "files/{{ item.src }}"
    dest: "{{ item.dest }}"
    mode: 0644
    owner: root
    group: wheel
  loop:
    - src: FreeBSD.conf
      dest: /usr/local/etc/pkg/repos/FreeBSD.conf

- name: Install Configuration
  when: custom_repo is defined
  copy:
    src: "files/{{ item.src }}"
    dest: "{{ item.dest }}"
    mode: 0644
    owner: root
    group: wheel
  loop:
    - src: disable_freebsd_upstream.conf
      dest: /usr/local/etc/pkg/repos/FreeBSD.conf
    - src: poudriere.pub
      dest: /usr/local/etc/pkg/poudriere.pub

- name: Install Configuration
  when: custom_repo is defined
  register: changed_config
  template:
    src: "{{ item.src }}"
    dest: "{{ item.dest }}"
    owner: root
    group: wheel
    mode: 0644
  loop:
    - { src: custom.conf.j2, dest: /usr/local/etc/pkg/repos/custom.conf }

- name: Install Configuration
  when: pkgbase_url is defined
  template:
    src: "{{ item.src }}"
    dest: "{{ item.dest }}"
    owner: root
    group: wheel
    mode: 0644
  loop:
    - { src: pkgbase.conf.j2, dest: /usr/local/etc/pkg/repos/pkgbase.conf }
# - name: Replace all packages with packages from new repo
#   command: pkg upgrade -f -y
#   when: changed_config.changed
