- name: generate ssh key
  command: "su -l {{ ansible_user }} -c \"ssh-keygen -t rsa -f /home/{{ ansible_user }}/.ssh/id_rsa -P ''\""
  args:
    creates: "/home/{{ ansible_user }}/.ssh/id_rsa"
    warn: False

- name: slurp public key
  slurp:
    src: "/home/{{ ansible_user }}/.ssh/id_rsa.pub"
  register: sshpubkey

# The following seems to be necessary to get rid of a newline:
- set_fact:
    sshpubkey: "{{ sshpubkey['content'] | b64decode | replace('\n', '') }}"

- name: set debian mirror in preseed file
  replace:
    dest: "{{ tftp_root }}/d-i/{{ di_dist }}/preseed.cfg"
    regexp: '^(d-i mirror/http/hostname string deb.debian.org)$'
    replace: '#\1\nd-i mirror/http/hostname string {{ deb_mirror }}'

- name: enable backports in preseed file
  replace:
    dest: "{{ tftp_root }}/d-i/{{ di_dist }}/preseed.cfg"
    regexp: '^#(apt-setup-udeb.*)$'
    replace: '\1'

- name: preseed client - add gnome-desktop, print-server
  replace:
    dest: "{{ tftp_root }}/d-i/{{ di_dist }}/preseed.cfg"
    regexp: '^(tasksel tasksel/first multiselect standard, ssh-server)$'
    replace: '#\1\ntasksel tasksel/first multiselect standard, ssh-server, gnome-desktop, print-server'

- name: preseed client - add firmware-linux, ansible/stretch-backports, git
  replace:
    dest: "{{ tftp_root }}/d-i/{{ di_dist }}/preseed.cfg"
    regexp: '^(d-i pkgsel/include string firmware-linux)$'
    replace: '#\1\nd-i pkgsel/include string firmware-linux ansible git'

- name: insert start of managed block
  replace:
    dest: "{{ tftp_root }}/d-i/{{ di_dist }}/preseed.cfg"
    regexp: '^(### This command is run just before the install finishes:)'
    replace: '#\1\n# BEGIN ANSIBLE MANAGED BLOCK preseed/late_command'

- name: insert end of managed block
  replace:
    dest: "{{ tftp_root }}/d-i/{{ di_dist }}/preseed.cfg"
    regexp: '^(## When installing.*)'
    replace: '# END ANSIBLE MANAGED BLOCK preseed/late_command\n#\1'

- name: insert block
  blockinfile:
    dest: "{{ tftp_root }}/d-i/{{ di_dist }}/preseed.cfg"
    insertafter: "^### This command is run just before the install finishes:"
    block: |
      d-i preseed/late_command string \
      mkdir -p /target/home/ansible/.ssh && \
      echo "{{ sshpubkey }}" >> /target/home/ansible/.ssh/authorized_keys ; \
      in-target chown -R ansible:ansible /home/ansible/.ssh/ ; \
      in-target chmod -R og= /home/ansible/.ssh/ ; \
      in-target ansible-pull --verbose --purge --extra-vars="run_in_installer=true" --url=git://{{ hostname }}/.git
    marker: "# {mark} ANSIBLE MANAGED BLOCK preseed/late_command"

- name: provide git repo if not available already
  git:
    repo: 'https://salsa.debian.org/andi/debian-lan-ansible.git'
    dest: "{{ repo_dir }}"
    update: no
  become_user: "ansible"

- name: install xinetd
  apt:
    name: xinetd

- name: enable git repo
  template:
    src: git-repo.j2
    dest: "/etc/xinetd.d/git-repo"
  notify: "reload xinetd"