#!/bin/bash -e
#
# fuse-nbd - Create a tar.gz from a binded fuse device
#
# Author: Alexsander Silva de Souza <alexsander.souza@canonical.com>
#
# Copyright (C) 2023 Canonical
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

ROOT_PARTITION=${ROOT_PARTITION:-1}
ROOT_MOUNT=${TMP_DIR}/root
DETECT_BLS_BOOT=${DETECT_BLS_BOOT:-0}
BOOT_MOUNT=${TMP_DIR}/boot

echo 'Mounting root partition...'
mount_part "${ROOT_PARTITION}" "${ROOT_MOUNT}"

if [ -f "$ROOT_MOUNT/etc/machine-id" ]; then
    echo 'reseting machine-id...'
    : >| "$ROOT_MOUNT/etc/machine-id"
fi

if [ -f "$ROOT_MOUNT/var/lib/cloud/instance" ]; then
    echo 'cleaning cloud-init state...'
    rm -f "$ROOT_MOUNT/var/log/cloud-init*.log" \
        "$ROOT_MOUNT/var/lib/cloud/instance"
    rm -rf "$ROOT_MOUNT/var/lib/cloud/instances"
fi

if [ -d curtin ] || [ -d "$CURTIN_HOOKS" ]; then
    echo 'Adding Curtin hooks...'
    cp -r "${CURTIN_HOOKS:-curtin}" "${ROOT_MOUNT}"
fi

echo "Creating MAAS image ${OUTPUT}..."
TARFILE=${OUTPUT%*.gz}
tar -Scpf "${TARFILE}" --acls --selinux --xattrs \
    --one-file-system \
    --exclude-backups \
    -C "$ROOT_MOUNT" .

if [ "${DETECT_BLS_BOOT}" -eq 1 ]; then
    echo "auto-detecting 'bls_boot' partition"
    mount_disk "${TMP_DIR}"/disk
    BOOT_PARTITION=$(parted -ms "${TMP_DIR}"/disk/nbd print | grep bls_boot | cut -d: -f1)
    if [ -n "$BOOT_PARTITION" ]; then
        mount_part "${BOOT_PARTITION}" "${BOOT_MOUNT}"
        tar -Supf "${TARFILE}" --acls --selinux --xattrs -C "$TMP_DIR" boot/
    fi
fi

gzip --best --force "${TARFILE}"

if [ -n "$MANIFEST" ]; then
    echo "Creating manifest..."
    # RPM on CentOS/RHEL 7 needs /dev mounted so it can use /dev/urandom
    mount -o bind /dev "${ROOT_MOUNT}/dev"
    chroot "${ROOT_MOUNT}" rpm -qa | sort -u -o "$MANIFEST"
    umount "${ROOT_MOUNT}/dev"
    grep -qs "${ROOT_MOUNT}/dev " /proc/mounts && umount -f "${ROOT_MOUNT}/dev"
fi

sync
fusermount -z -u "${ROOT_MOUNT}"
grep -qs "${ROOT_MOUNT} " /proc/mounts && umount -f "${ROOT_MOUNT}"
echo 'Done'
