#!/bin/bash

# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# This script runs on target pre installation of nvidia-l4t-initrd debian package.

set -e

init_var() {
	INITRD="/boot/initrd"
	INITRD_BAK_DIR="/var/tmp/nvidia-l4t-initrd.backup"
	INSTALL_FLAG_FILE="nvidia-l4t-initrd.install"

	# Crypttab path in initrd
	CRYPTTAB="etc/crypttab"
	LUKS_DEVICES=""
}

# Check if disk encryption is enabled by looking for LUKS devices
is_disk_encryption_enabled() {
	LUKS_DEVICES=$(blkid | grep TYPE=\"crypto_LUKS\")

	# LUKS devices are found
	if [ -n "$LUKS_DEVICES" ]; then
		return 0
	fi

	return 1
}

# Back up crypttab file from the initrd
back_up_crypttab() {
	pushd "${INITRD_BAK_DIR}" > /dev/null

	# Back up crypttab from the initrd
	gunzip -c "${INITRD}" | sudo cpio --quiet -idmu "${CRYPTTAB}"

	if [[ ! -f "${INITRD_BAK_DIR}/${CRYPTTAB}" ]]; then
		echo "ERROR. ${INITRD_BAK_DIR}/${CRYPTTAB} not found in ${INITRD}."
		exit 1
	fi

	popd > /dev/null
}

init_var

# Create the backup directory
mkdir -p "${INITRD_BAK_DIR}"
# The temp file indicating that it's nvidia-l4t-initrd Debian package installation
touch "${INITRD_BAK_DIR}/${INSTALL_FLAG_FILE}"

# If LUKS devices are found, back up crypttab
if is_disk_encryption_enabled; then
	echo "Back up ${CRYPTTAB} from initrd since disk encryption is enabled."
	echo "LUKS-encrypted devices found:"
	echo "$LUKS_DEVICES"

	back_up_crypttab
fi
