- name: Create chroot mount point
  file:
    path: "{{ chroot_mount_point }}"
    state: directory

- name: Bind mount loop file at chroot_mount_point
  command: "mount -o bind {{ loop_mount_location }} {{ chroot_mount_point }}"

- name: Mount proc into chroot
  command: "mount -t proc {{ item }} {{ chroot_mount_point }}{{ item }}"
  with_items:
    - "/proc"

- name: Mount binfmt_misc into chroot
  command: "mount -t binfmt_misc {{ item }} {{ chroot_mount_point }}{{ item }}"
  with_items:
    - "/proc/sys/fs/binfmt_misc"

- name: Mount remaining root-level dirs into chroot
  command: "mount --bind {{ item }} {{ chroot_mount_point }}{{ item }}"
  with_items:
    - "/sys"
    - "/dev"
    - "/run"

# While building the OS image, we need DNS resolution to work correctly for
# some of the tools inside the chroot (like apt). Without taking DNS config
# from the host build system, resolution only works when the host build system
# and the target OS use the same DNS resolution tool. Our Ubuntu 20.04 config
# uses systemd-resolved and the build environment uses resolvconf.
- name: Backup chroot's resolv.conf
  command: "mv {{ chroot_mount_point }}/etc/resolv.conf {{ chroot_mount_point }}/etc/resolv.conf.bak"

- name: Copy hosts's resolv.conf into chroot
  command: "cp /etc/resolv.conf {{ chroot_mount_point }}/etc/resolv.conf"

# While building images inside the chroot, we don't want to start/stop services on the host
# We re-enable these links in teardown_chroot
- name: Check whether service management executables are disabled
  command: "readlink -f {{ chroot_mount_point }}{{ item }}"
  register: links
  with_items:
    - "{{ os_service_management_executables }}"

- name: Disable service management executables
  shell: "mv {{ item.cmd[2] }} {{ item.cmd[2] }}.bak && ln -s /bin/true {{ item.cmd[2] }}"
  with_items: "{{ links.results }}"
  when: item.stdout != '/bin/true'

# Here we are locking any packages that might control service management executables
# because we had previously disabled those by symlinking to /bin/true. If these packages
# update during the os build process, it will overwrite the symlink to /bin/true, and
# cause those executables to start processing things.
- name: Lock packages that control service management executables
  command: "sudo apt-mark hold {{ item }}"
  with_items:
    - "{{ os_service_management_packages }}"
  when: os_release_name == 'focal'
