# choose a node for tasks that should only run on (any) one node, e.g. when writing to /etc/pve
- name: Select the primary node
  set_fact:
    is_primary: '{{ nodes is defined and inventory_hostname == (nodes | map(attribute="inventory_hostname") | sort | first) }}'

- 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: Disable SSH password authentication
  lineinfile:
    path: /etc/ssh/sshd_config
    regexp: '^#?{{ item.key }}'
    line: '{{ item.key }} {{ item.value }}'
  loop:
    - key: PasswordAuthentication
      value: 'no'
    - key: PermitRootLogin
      value: 'prohibit-password'
  notify: reload sshd

- include_tasks: network.yml

- name: Disable enterprise repositories
  apt_repository:
    repo: '{{ item }}'
    state: absent
    update_cache: no
  loop:
    - 'deb https://enterprise.proxmox.com/debian/pve {{ ansible_distribution_release }} pve-enterprise'
    - 'deb https://enterprise.proxmox.com/debian/ceph-quincy {{ ansible_distribution_release }} enterprise'
  notify: update package cache

- name: Enable no-subscription repository
  apt_repository:
    repo: 'deb http://download.proxmox.com/debian/pve {{ ansible_distribution_release }} pve-no-subscription'
    update_cache: no
  notify: update package cache

- meta: flush_handlers

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

- name: Set up sysctls
  copy:
    dest: /etc/sysctl.d/local.conf
    src: sysctl.conf

- name: Set domain for ACME certificate renewals
  command:
    cmd: 'pvenode config set --acme domains={{ interfaces | selectattr("name", "==", "lo")
             | map(attribute="ip_addresses") | flatten | map(attribute="dns_name")
             | sort | unique | join(";") }}'
  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

- include_tasks: user.yml