#!/bin/bash
#
# Copyright (c) 2013 National Instruments
#
# Format rootfs and the config volumes and delete the runmode kernel
#

# include common utilities
if [ -e /etc/init.d/mountutils ]; then
	source /etc/init.d/mountutils
fi

# Bail out on first error
set -E -o errexit

COMMAND_RETRY_COUNT=30
COMMAND_RETRY_SLEEP=1

arch=`uname -m`

NETCFG_MODE=bypass

ENCRYPT=no
ENCRYPT_BACKUP=no
ENCRYPT_PCR_SET=""
ENCRYPT_DICT_LOCKOUT="disable"

NETCFG_TMP=/tmp/netconfig.$$
declare -r BASENAME=${0##*/}

NINETCFGUTIL=/usr/local/natinst/bin/ninetcfgutil

NILRTDISKCRYPT=/usr/sbin/nilrtdiskcrypt

if [ "$arch" = "x86_64" ]; then
	LABEL_TYPE=$(lsblk -lno PARTLABEL | grep -q nirootfs && echo PARTLABEL || echo LABEL)
	CONFIGFS_DEV=/dev/$(lsblk -l -n -o $LABEL_TYPE,NAME | grep '^niconfig '| tr -s ' ' | cut -d' ' -f2)
	ROOTFS_DEV=/dev/$(lsblk -l -n -o $LABEL_TYPE,NAME | grep '^nirootfs '| tr -s ' ' | cut -d' ' -f2)
fi

CONFIG_MOUNT_POINT="/etc/natinst/share"
ROOTFS_MOUNT_POINT="/mnt/userfs"

TARGETINFO_PATH="$CONFIG_MOUNT_POINT/targetinfo.ini"

# List of returnable errors
declare -Ar EXITCODES=(
	[UNSPECIFIED]=1		# No reason specified
	[UNKNOWN_ERROR]=2	# Unexpected exit code encountered
	[INVALID_ARGUMENT]=3	# An invalid combination of arguments was specified
	[INVALID_FSTYPE]=4	# An invalid fstype was specified
	[ILLTIMED]=5            # Called at an inappropriate time
	[INVALID_ARCH]=6        # Running an unsupported processor architecture
	[NO_TPM_HARDWARE]=7     # Could not detect a TPM chip
	[NO_KEY_BACKUP_DEVICE]=8     # Partition to store backup key could not be found; perhaps it's mislabeled or not plugged in
)

# $1: exit code (key from EXITCODES)
# ${@:2}: text
die()
{
	echo -e "*** Error: $0:${BASH_LINENO[1]}: ${@:2}" >&2
	exit ${EXITCODES[$1]}
}

die_with_usage()
{
	echo -e "*** Error: ${@:2}" >&2
	usage
	exit ${EXITCODES[$1]}
}

# $1: source path
# $2: line no
# $3: function name
# $4: exit code
handle_err()
{
	echo "*** Error: $1:$2 (fn=$3): Unexpected status code $4" >&2
	exit ${EXITCODES[UNKNOWN_ERROR]}
}

# Retry loop for commands: Executes the specified command repeatedly
# until it either exits with 0 or max number of retries are exhausted.
# $@: Command and parameters
with_retry()
{
	for attemptItr in `seq 1 "$COMMAND_RETRY_COUNT"`; do
		if "$@"; then
			return 0
		fi

		echo "$* failed with $? (attempt $attemptItr)" >&2
		sleep "$COMMAND_RETRY_SLEEP"
	done

	echo "ERROR: $* failed ($COMMAND_RETRY_COUNT attempts)" >&2
	return 1
}

services_stop () {
	/etc/init.d/systemWebServer stop || true
	/etc/init.d/sshd stop || true
	/etc/init.d/niauth stop || true
}

services_start () {
	/etc/init.d/niauth start || true
	/etc/init.d/sshd start || true
	/etc/init.d/systemWebServer start || true
}

install_default_err_handler()
{
	trap 'handle_err ${BASH_SOURCE} ${LINENO} ${FUNCNAME:-unknown} $?' ERR
}

supported_fstypes()
{
	hash /usr/sbin/ubiformat 2>/dev/null && [ "$arch" = "armv7l" ] && echo -n "ubifs," || true
	hash /sbin/mkfs.ext4 2>/dev/null && [ "$arch" = "x86_64" ] && echo -n "ext4," || true
}

# Find the filesystem type of the root partition (or volume)
print_root_fstype()
{
	if [ "$OSMODE" != runmode ]; then
		grep " $ROOTFS_MOUNT_POINT " /proc/mounts | awk '{print $3}'
	else
		# regarding skipping rootfs, see "What is rootfs?" at
		# https://www.kernel.org/doc/Documentation/filesystems/ramfs-rootfs-initramfs.txt
		grep " / " /proc/mounts | awk '{if ($3 != "rootfs") print $3}'
	fi
}

# Find the filesystem type of the config partition (or volume)
print_config_fstype()
{
	grep " $CONFIG_MOUNT_POINT " /proc/mounts | awk '{print $3}'
}

umount_config()
{
	with_retry /etc/init.d/populateconfig stop
	with_retry /etc/init.d/mountconfig stop
}

umount_rootfs()
{
	with_retry /etc/init.d/mountcompatibility stop
	with_retry /etc/init.d/mountuserfs stop
}

# restore config partition after format
# $1: exit code
# $2: line number of trap (if failing)
mount_config()
{
	with_retry /etc/init.d/mountconfig start
	with_retry /etc/init.d/populateconfig start

	if (( $1 != 0 )); then
		die UNKNOWN_ERROR "Format failed, line $2, status code $1"
	fi
}

# restore root partition after format
# $1: exit code
# $2: line number of trap (if failing)
mount_rootfs()
{
	with_retry /etc/init.d/mountuserfs start
	with_retry /etc/init.d/mountcompatibility start

	# Move the restore files back to the rootfs
	if [ -e /tmp/restore ]; then
		mkdir -p "$ROOTFS_MOUNT_POINT/.restore"
		mv /tmp/restore/* "$ROOTFS_MOUNT_POINT/.restore"
		rmdir /tmp/restore
	fi

	if (( $1 != 0 )); then
		die UNKNOWN_ERROR "Format failed, line $2, status code $1"
	fi
}

# Format the rootfs volume
# $1: filesystem to use (currently "ubifs" or "ext4")
# $2: root device (defaults to $ROOTFS_DEV, only works for x86_64 on ARM is ignored)
format_rootfs()
{
	trap 'mount_rootfs $? $LINENO' ERR

	# Backup the restore files to the tmp dir
	if [ -e "$ROOTFS_MOUNT_POINT/.restore" ]; then
		mkdir -p /tmp/restore
		cp -R "$ROOTFS_MOUNT_POINT"/.restore/* /tmp/restore/
	fi

	# remove Zynq kernel
	rm -f /boot/linux_runmode.itb

	# remove any old kernel-dev files which were deposited in the /boot partition
	rm -f /boot/Module.symvers-*
	rm -f /boot/config-*
	rm -f /boot/System.map-*

	# remove x64 kernel
	if [ -e /boot/runmode  ]; then
		rm -R /boot/runmode
		mkdir /boot/runmode
	fi

	# fstype is validated before calling format_rootfs
	case "$1" in
	  ubifs)
		local partition_label="root"
		local volume_number="0"
		local volume_label="rootfs"
		format_ubi_volume "$partition_label" "$volume_number" "$volume_label"
		;;
	  ext4)
		local volume_label="nirootfs"
		local options=""
		if [ "$ENCRYPT" = yes ]; then
			options="-O metadata_csum,64bit"
		fi
		mkfs.ext4 -q -F -L $volume_label $options ${2:-$ROOTFS_DEV}
		;;
	esac

	install_default_err_handler
}

# Format the config volume
# $1: filesystem to use (currently "ubifs" or "ext4")
# $2: configfs device (defaults to $CONFIGFS_DEV, only works for x86_64 on ARM is ignored)
format_config()
{
	trap 'mount_config $? $LINENO' ERR

	# fstype is validated before calling format_config
	case "$1" in
	  ubifs)
		local partition_label="boot-config"
		local volume_number="3"
		local volume_label="config"
		format_ubi_volume "$partition_label" "$volume_number" "$volume_label"
		;;
	  ext4)
		local volume_label="niconfig"
		local options=""
		if [ "$ENCRYPT" = yes ]; then
			options="-O metadata_csum,64bit"
		fi
		mkfs.ext4 -q -F -L $volume_label $options ${2:-$CONFIGFS_DEV}
		;;
	esac

	install_default_err_handler
}

usage()
{
	if [ "$OSMODE" != runmode ]; then
		cat >&2 <<-EOF
		Usage: $BASENAME [-f -t <type> [-c][-r][-n <mode>][-e]|-s [-c]|-l] [-B <fslabel>] [-P <pcrset>] [-L keep|disable]

		-f	Format the volume
		-h	Print this help
		-s	List current filesystem type
		-l	List possible filesystem types

		-t	Filesystem type
		-c	Format the config volume (otherwise rootfs + kernel)
		-r	Relaunch the system webserver after format
		-e	Encrypt volume using a new generated disk key stored in the TPM
		-B	Backup encryption keys to the filesystem labeled <fslabel> (normally on USB storage)
		-P	Comma separated set of PCR registers to seal disk keys
		-L	Specifies dictionary lockout configuration:
		        keep: Do not change current configuration
		        disable: Disable dictionary lockout (default)
		-n	Preserve network config according to <mode>:
		        all		Preserve all settings
		        primary		Preserve primary, reset secondary
		        none		Reset all settings
		        bypass		No configuration handling (default)

		Examples:

		$BASENAME -f -t <type>        - format the rootfs as <type> fs
		$BASENAME -f -t <type> -c -e  - format and encrypt configfs & rootfs
		$BASENAME -s -c		- print the filesystem type of the config volume
		$BASENAME -l		- list possible filesystem types (',' separated)

		EOF
	else
		cat >&2 <<-EOF
		Usage: $BASENAME [-s [-c]|-l]

		-h	Print this help
		-s	List current filesystem type
		-l	List supported filesystem types
		-c	Config volume (otherwise rootfs + kernel)

		Examples:

		$BASENAME -s		print the filesystem type of the rootfs volume
		$BASENAME -s -c		print the filesystem type of the config volume

		EOF
	fi
}

netconfig_pre()
{
	[[ $NETCFG_MODE == bypass || $NETCFG_MODE == none ]] && return 0
	rm -rf $NETCFG_TMP
	mkdir -p $NETCFG_TMP
	OPTS=()
	case "$NETCFG_MODE" in
		all) OPTS+=(-g secondary) ;&
		primary) OPTS+=(-g primary) ;;
	esac
	$NINETCFGUTIL save -d $NETCFG_TMP ${OPTS[@]}
}

netconfig_post()
{
	case "$NETCFG_MODE" in
		bypass)
			return 0 ;;
		all|primary)
			$NINETCFGUTIL restore -d $NETCFG_TMP
			rm -rf $NETCFG_TMP
			;;
		none)
			rm -rf $NETCFG_TMP
			mkdir -p $NETCFG_TMP
			$NINETCFGUTIL erase -d $NETCFG_TMP -g primary -g secondary
			rm -rf $NETCFG_TMP
			mkdir -p $NETCFG_TMP
			$NINETCFGUTIL pulldefault -d $NETCFG_TMP -g primary -g secondary
			rm -rf $NETCFG_TMP
			;;
	esac
}

targetinfo_restore()
{
	SUPPORTED_FS=$(supported_fstypes)
	CURRENT_FS=$(print_root_fstype)
	cat >"$TARGETINFO_PATH" <<-EOF
	[FileSystem]
	Current=$CURRENT_FS
	Supported=$SUPPORTED_FS
	EOF
}

install_default_err_handler

# Are we running in safemode, restore mode, or runmode?
if [ -f /etc/natinst/safemode ]; then
	OSMODE=safemode
elif [ -f /etc/natinst/restoremode ]; then
	OSMODE=restore
else
	# in runmode the rootfs is in use, restricting available options
	OSMODE=runmode
fi

case "$(runlevel)" in
*\ 6|*\ 0) die ILLTIMED "Called during shutdown; aborting." ;;
esac

# Script invoked with no command-line args?
if [ $# -eq "0" ]
then
	die_with_usage INVALID_ARGUMENT "No command-line arguments specified."
fi

while getopts "fhsln:t:creB:P:L:" Option
do
	case $Option in
		f)	MODE=format;;
		h)	usage; exit 0 ;;
		s)	MODE=status;;
		l)	MODE=list;;
		t)	TYPE=$OPTARG;;
		c)	VOL=config;;
		r)	RELAUNCH=yes;;
		e)	ENCRYPT=yes;;
		B)	ENCRYPT_BACKUP=yes && ENCRYPT_BACKUP_LABEL="$OPTARG";;
		P)	ENCRYPT_PCR_SET="$OPTARG";;
		L)	ENCRYPT_DICT_LOCKOUT="$OPTARG";;
		n)	NETCFG_MODE="$OPTARG";;
		*)	usage;;
	esac
done

if [ "$MODE" = format -a "$OSMODE" = runmode ]; then
	die_with_usage INVALID_ARGUMENT "Formatting is not available in runmode."
fi

if [ "$RELAUNCH" = yes ]; then
	if [ "$MODE" != format -o "$VOL" != config ]; then
		die_with_usage INVALID_ARGUMENT \
			"relaunch (-r) can only be used when formatting config partition (-f -c)"
	fi
	if [ "$OSMODE" = restore ]; then
		die_with_usage INVALID_ARGUMENT \
			"relaunch (-r) cannot be used in restore mode"
	fi
fi

if [ -n "$TYPE" ]; then
	if [ "$MODE" = status -o "$MODE" = list ]; then
		die_with_usage INVALID_ARGUMENT \
			"fstype option (-t) cannot be used with status -s or -l"
	fi
fi

if [ "$MODE" = list -a -n "$VOL" ]; then
	die_with_usage INVALID_ARGUMENT \
		"Volume name (-v) cannot be specified when listing fs types (-l)"
fi

if [ "$MODE" != format -a "$NETCFG_MODE" != "bypass" ]; then
	die_with_usage INVALID_ARGUMENT \
		"Network settings (-n) can only be specified when formatting (-f)"
fi

case "$NETCFG_MODE" in
	all|primary|none|bypass) ;;
	*)
		die_with_usage INVALID_ARGUMENT \
			"Unknown network config setting $NETCFG_MODE"
		;;
esac

if [ "$MODE" = format ]; then
	if [ -z "$TYPE" ]; then
		die_with_usage INVALID_FSTYPE "No filesystem type was specified"
	fi

	[[ $(supported_fstypes) =~ (^|,)$TYPE(,) ]] || die_with_usage INVALID_FSTYPE "Invalid fstype '$TYPE'"
fi

if [ "$ENCRYPT" = yes ]; then
	if [ "$MODE" != format -o "$VOL" != config ]; then
		die_with_usage INVALID_ARGUMENT \
			"Encryption can be only be used when performing a full format including config (-f -c)"
	fi

	if [ "$arch" != "x86_64" ]; then
		die_with_usage INVALID_ARCH \
			"Encryption can be only be used on x86_64 machines"
	fi

	if ! ${NILRTDISKCRYPT}_canformat; then
		die_with_usage NO_TPM_HARDWARE \
			"The TPM chip on this machine could not be detected (does it have one?)"
	fi

	# Sanity check, unlikely to hit
	# Encrypted disk won't boot unless system is provisioned with initramfs enabled
	enable_initramfs="`/sbin/fw_printenv enable_initramfs 2>/dev/null | cut -d= -f2`" || true
	[ -n "$enable_initramfs" ] || enable_initramfs="0"
	if [ "$enable_initramfs" -lt 1 ]; then
		die_with_usage UNKNOWN_ERROR \
			"System must be provisioned with initramfs enabled"
	fi
fi

if [ "$ENCRYPT_BACKUP" = yes ]; then
	if [ "$ENCRYPT" != yes ]; then
		die_with_usage INVALID_ARGUMENT \
			"Backing up encryption keys only works when formatting with encryption enabled (-e)"
	fi

	if [ -z "$ENCRYPT_BACKUP_LABEL" ]; then
		die_with_usage INVALID_ARGUMENT \
			"No filesystem label specified to the -B arg"
	fi

	# it's best to capture this error here as early as possible before we umount, stop services or call
	# nilrtdiskcrypt/luks to nuke filesystems
	bkpDevice=$(lsblk -l -n -o LABEL,NAME | grep "^$ENCRYPT_BACKUP_LABEL " | tr -s ' ' | cut -d' ' -f2 || true )
	if [ -z "$bkpDevice" ]; then
		die_with_usage NO_KEY_BACKUP_DEVICE \
			"Could not detect block device containing filesystem label $ENCRYPT_BACKUP_LABEL"
	fi
fi

if [ "$ENCRYPT_DICT_LOCKOUT" != "keep" -a "$ENCRYPT_DICT_LOCKOUT" != "disable" ]; then
	die_with_usage INVALID_ARGUMENT \
		"Dictionary lockout mode must be 'keep' or 'disable'"
fi

case "$MODE" in
	format)
		netconfig_pre
		services_stop

		umount_config
		umount_rootfs

		configfs_dev="$CONFIGFS_DEV"
		rootfs_dev="$ROOTFS_DEV"

		# Only if the machine has TPM hardware support (x64 targets for now)
		if [ "$arch" = "x86_64" ] && [ -e "/dev/tpm0" ] && ${NILRTDISKCRYPT}_canformat; then
			# unconditionally wipe keys to ensure secure deletion of previously encrypted data,
			# this needs to happen regardless of current format type (both encrypted or not)
			# and will make data unrecoverable on both config & rootfs
			${NILRTDISKCRYPT}_close -d "$configfs_dev" -d "$rootfs_dev"
			${NILRTDISKCRYPT}_wipe -k 0 -k 1

			if [ "$ENCRYPT" = yes ]; then
				if [ "$ENCRYPT_DICT_LOCKOUT" == "disable" ]; then
					${NILRTDISKCRYPT}_dictionarylockout -d
				fi

				bkp_arg=""
				pcrset_arg=""
				[ "$ENCRYPT_BACKUP" = yes ] && bkp_arg="-B $ENCRYPT_BACKUP_LABEL"
				[ -n "$ENCRYPT_PCR_SET" ] && pcrset_arg="-P $ENCRYPT_PCR_SET"
				luks_dev=( $("${NILRTDISKCRYPT}_format" -s 0 -d "$configfs_dev" -d "$rootfs_dev" $bkp_arg $pcrset_arg) )
				configfs_dev=${luks_dev[0]}
				rootfs_dev=${luks_dev[1]}
			fi
		fi

		if [ "$VOL" = config ]; then
			# We're forcing rootfs formatting even though the user requested config because
			# we need to support secure deletion (once one partition is formatted the key is
			# deleted) so by deleting the configfs we invalidate the rootfs. In the non-encrypt
			# case we can be unable to mount already encrypted rootfs after configfs was wiped
			# because the key was missing.
			if [ "$ENCRYPT" = yes ] || ${NILRTDISKCRYPT}_canopen -d "$rootfs_dev" 2>/dev/null; then
				format_rootfs "$TYPE" "$rootfs_dev"
			fi
			format_config "$TYPE" "$configfs_dev"
		else
			if ${NILRTDISKCRYPT}_canopen -d "$configfs_dev" 2>/dev/null; then
				format_config "$TYPE" "$configfs_dev"
			fi
			format_rootfs "$TYPE" "$rootfs_dev"
		fi

		# configfs needs to be mounted before rootfs otherwise only one *etc/natinst/share will be mounted
		# (this may be a bug in the mount* initscripts - Ionel)
		mount_config 0
		mount_rootfs 0

		netconfig_post

		# targetinfo.ini needs to be restored or it will not be recreated until a reboot into safemode
		targetinfo_restore

		if [ "$RELAUNCH" = yes ]; then
			services_start
		fi
	;;
	status)
		if [ "$VOL" = config ]; then
			print_config_fstype
		else
			print_root_fstype
		fi
	;;
	list)
		echo -n $(supported_fstypes)
	;;
esac

exit 0
