- name: Set hostname
  hostname:
    name: '{{ inventory_hostname }}'

- name: Set up hosts file
  template:
    dest: /etc/hosts
    src: hosts.j2

- name: Set up resolv.conf
  template:
    dest: /etc/resolv.conf
    src: resolv.conf.j2
    mode: 0644

- name: Set up debian repositories
  template:
    dest: /etc/apt/sources.list
    src: sources.list.j2
    mode: 0644
  notify: update package cache
  when: debian_release is defined

- name: Disable enterprise repositories
  apt_repository:
    repo: 'deb https://enterprise.proxmox.com/debian/pbs {{ ansible_distribution_release }} pbs-enterprise'
    state: absent

- name: Enable no-subscription repository
  apt_repository:
    repo: 'deb http://download.proxmox.com/debian/pbs {{ ansible_distribution_release }} pbs-no-subscription'

- name: Install essential packages
  package:
    name:
      - git
      - rsync
      - vim
      - tmux

- name: Add rules to rename network interfaces
  template:
    dest: /etc/udev/rules.d/10-network.rules
    src: 10-network.rules.j2
    mode: 0644
  notify: reboot

- name: Include interfaces.d definitions
  copy:
    dest: /etc/network/interfaces
    content: 'source /etc/network/interfaces.d/*'
  notify: reload interfaces

- name: Set up interfaces
  template:
    dest: /etc/network/interfaces.d/ansible.intf
    src: ansible.intf.j2
    mode: 0644
  notify: reload interfaces

- name: Run SSH instance in management VRF
  when: interfaces | selectattr('vrf') | selectattr('vrf.name', '==', 'mgmt')
  block:
    - name: Configure SSH instance in management VRF
      copy:
        dest: /etc/ssh/
        src: sshd_config.mgmt
        mode: 0644
      notify: reboot

    - name: Set up a SSH instance in management VRF
      copy:
        dest: /etc/systemd/system/
        src: sshd@mgmt.service
        mode: 0644
      notify: reboot

    - name: Enable management SSH
      service:
        name: sshd@mgmt
        enabled: yes
      notify: reboot

    - name: Disble SSH in default VRF
      service:
        name: ssh
        enabled: no
      notify: reboot

- name: Set domain for ACME certificate renewals
  command:
    cmd: 'proxmox-backup-manager node update --acmedomain0 domain={{ interfaces | selectattr("name", "==", "lo")
             | map(attribute="ip_addresses") | flatten | map(attribute="dns_name") | first }}'
  changed_when: false # maybe write a proper check if certificate requests are ever ansibled

- name: Set SMTP relay
  lineinfile:
    path: /etc/postfix/main.cf
    regexp: '^relayhost ='
    line: 'relayhost = {{ mail_relay | default("") }}'
  notify: reload postfix

- include_tasks: firewall.yml