# Get the root partition device
# ==============================================================================

ROOT_PART=$(swupdate -g)
echo "Root partition is ${ROOT_PART}"

# Get the partition label of the root partition
# ==============================================================================

DISK_DEVICE_NAME=$(lsblk -ndo pkname "${ROOT_PART}")
DISK_PARTITION_TYPE=$(lsblk -dno PTTYPE "/dev/${DISK_DEVICE_NAME}")

echo "Root partition is on device ${DISK_DEVICE_NAME} - type ${DISK_PARTITION_TYPE}"

# Use partlabel for GPT disk, as it's more reliable than the filesystem label
# Fallback to label for legacy DOS/MBR disk
if [ "${DISK_PARTITION_TYPE}" == "gpt" ]; then
  ROOT_PARTLABEL=$(lsblk -dno PARTLABEL "${ROOT_PART}")
else
  echo "Using MBR is not supported"
  exit 1
fi

echo "Root partition label is ${ROOT_PARTLABEL}"

case $ROOT_PARTLABEL in
    rootfs0 )
        echo "We are running copy0 -> Use copy1 in the SWU file"
        SWUPDATE_ARGS="${SWUPDATE_ARGS} -e stable,copy1"
    ;;
    rootfs1 )
        echo "We are running copy1 -> Use copy0 in the SWU file"
        SWUPDATE_ARGS="${SWUPDATE_ARGS} -e stable,copy0"
    ;;
    * )
        >&2 echo "Root partition label ${ROOT_PARTLABEL} is invalid"
        exit 1
        ;;
esac
