#!/bin/bash
# Verify install path
## kola:
##   timeoutMin: 30
##   tags: "needs-internet"
##   platforms: qemu  # additionalDisks is only supported on qemu
##   additionalDisks: ["20G"]
#
# Copyright (C) 2022 Red Hat, Inc.

set -xeuo pipefail

IMAGE=quay.io/centos-bootc/fedora-bootc-dev:eln
# TODO: better detect this, e.g. look for an empty device
DEV=/dev/vda

# Always work out of a temporary directory
cd $(mktemp -d)

case "${AUTOPKGTEST_REBOOT_MARK:-}" in
  "")
    mkdir -p ~/.config/containers
    cp -a /etc/ostree/auth.json ~/.config/containers
    mkdir -p usr/{lib,bin}
    cp -a /usr/lib/bootc usr/lib
    cp -a /usr/bin/bootc usr/bin
    cat > Dockerfile << EOF
    FROM ${IMAGE}
    COPY usr usr
EOF
    podman build -t localhost/testimage .
    podman run --rm -ti --privileged --pid=host --env RUST_LOG=error,bootc_lib::install=debug \
      localhost/testimage bootc install to-disk --skip-fetch-check --karg=foo=bar ${DEV}
    # In theory we could e.g. wipe the bootloader setup on the primary disk, then reboot;
    # but for now let's just sanity test that the install command executes.
    lsblk ${DEV}
    mount /dev/vda3 /var/mnt
    grep foo=bar /var/mnt/loader/entries/*.conf
    grep localtestkarg=somevalue /var/mnt/loader/entries/*.conf
    grep -Ee '^linux /boot/ostree' /var/mnt/loader/entries/*.conf
    umount /var/mnt
    echo "ok install"
    mount /dev/vda4 /var/mnt
    ls -dZ /var/mnt |grep ':root_t:'
    umount /var/mnt

    # Now test install to-filesystem
    # Wipe the device
    ls ${DEV}* | tac | xargs wipefs -af
    # This prepares the device and also runs podman directliy
    bootc internal-tests test-install-filesystem ${IMAGE} ${DEV}
    ;;
  *) echo "unexpected mark: ${AUTOPKGTEST_REBOOT_MARK}"; exit 1;;
esac
