#!/usr/bin/env bash
# Copyright (c) 2025 SUSE LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#

# Set image build defaults, blocksize is an empty string
PROFILE="Base"
LARGEBLOCK=false

# Print usage
usage(){
  cat <<-EOF
  =====================================
  SUSE Linux Micro 6.1 Kiwi SDK Builder
  =====================================

  Usage: ${0} [-p <profile>] [-b]

  Profile Options (-p):
  * Default: RAW Disk Image with default packages (incl. Podman & KVM)
  * Default-SelfInstall: SelfInstall ISO with default packages
  * Default-RPi: RAW Disk Image for Raspberry Pi (aarch64 only with MBR)
  * Base: RAW Disk Image with reduced package set (no KVM)
  * Base-SelfInstall: SelfInstall ISO with reduced packages
  * Base-RT: RAW Disk Image with reduced packages and kernel-rt
  * Base-RT-SelfInstall: SelfInstall ISO with reduced packages and kernel-rt
  * Base-RT-RPi: RAW Disk image for Raspberry Pi with kernel-rt (aarch64 only with MBR)
  * Base-RPi: RAW Disk Image for Raspberry Pi with reduced packages (aarch64 only with MBR)

  4096 Blocksize (-b): If specified, use a 4096 blocksize (rather than 512) when generating the image.

  NOTE: If both options are omitted, the "Base" profile with a standard "512" blocksize is used.
EOF
}

# Grab CLI options and handle
while getopts 'p:bh' OPTION; do
  case "${OPTION}" in
    p)
      PROFILE="${OPTARG}"
      ;;
    b)
      LARGEBLOCK=true
      ;;
    ?)
      usage && exit 2
      ;;
  esac
done

# To avoid wasting time, perform the loop creation test first, and exit with a warning to re-run.
# This only happens when the container hasn't been ran on the host before, and is avoided by mounting /dev/ into the image.
qemu-img create /tmp/output/test.img 1M
if LOOP=$(losetup -f --show /tmp/output/test.img); then
  rm -f /tmp/output/test.img
  losetup -d $LOOP
else
  echo -e "\nERROR: Early loop device test failed, please retry the container run."
  exit 1
fi

# Grab local SLE Micro repos and create a list to use as part of the image build
REPOS=`for i in $(cat /micro-sdk/repos/*.repo | awk '/baseurl/ {split($0,string,"="); print string[2]}'); do echo -n "--add-repo $i "; done`

if $LARGEBLOCK; then
  mv /micro-sdk/defs/SL-Micro.kiwi.4096 /micro-sdk/defs/SL-Micro.kiwi
fi

# Build the image
kiwi-ng --debug --profile $PROFILE system build \
    --description /micro-sdk/defs --target-dir /tmp/output --ignore-repos-used-for-build $REPOS

# Print output
RESULT=$?
if [ $RESULT -eq 0 ]; then
  echo -e "\n\nINFO: Image build successful, generated images are available in the 'output' directory."
else
  echo -e "\n\nERROR: Failed to build the image, please see above logs."
fi
