# These were disabled by setup_chroot
- name: Check whether service management executables are enabled
  command: "readlink -f {{ chroot_mount_point }}{{ item }}"
  register: links
  with_items:
    - "{{ os_service_management_executables }}"

- name: Enable invoke-rc.d and service
  fail:
    msg: "Expected {{ item }} to be a symlink to /bin/true but it was not. Maybe apt updated this during the build process?"
  with_items: "{{ links.results }}"
  when: item.stdout != '/bin/true'

- name: Enable invoke-rc.d and service
  shell: "mv {{ item.cmd[2] }}.bak {{ item.cmd[2] }}"
  with_items: "{{ links.results }}"
  when: item.stdout == '/bin/true'

- name: Unlock packages that control service management executables
  command: "sudo apt-mark unhold {{ item }}"
  with_items:
    - "{{ os_service_management_packages }}"
  when: os_release_name == 'focal'

- name: Restore chroot's resolv.conf
  command: "mv {{ chroot_mount_point }}/etc/resolv.conf.bak {{ chroot_mount_point }}/etc/resolv.conf"

- name: Unmount sys, dev, proc from chroot
  command: "umount {{ chroot_mount_point }}{{ item }}"
  with_items:
    # Note: if any of these fail to unmount, it's probably because some process is running in the chroot.
    # `service` and `invoke-rc.d` should be disabled whenever building in a chroot to prevent processes from
    # running, but there could be another way that a process has been launched.
    - "/run"
    - "/dev"
    - "/sys"
    - "/proc/sys/fs/binfmt_misc"
    - "/proc"
    - "/"
  tags:
    - unmount_only

- name: Remove chroot mount point
  command: "rmdir {{ chroot_mount_point }}"
  args:
    warn: no
