#!/bin/sh

. /lib/partman/lib/base.sh

ARCH="$(archdetect)"
case $ARCH in
    i386/*|amd64/*)
	new_efi_fs=fat32
	;;
    *)
	new_efi_fs=fat16
	;;
esac

if search-path mkfs.fat; then
	MKFS_FAT=mkfs.fat
else
	MKFS_FAT=mkdosfs
fi

enable_swap
for dev in $DEVICES/*; do
	[ -d "$dev" ] || continue
	cd $dev
	partitions=
	open_dialog PARTITIONS
	while { read_line num id size type fs path name; [ "$id" ]; }; do
		[ "$fs" != free ] || continue
		partitions="$partitions $id,$num"
	done
	close_dialog
 
	for part in $partitions; do
		id=${part%,*}
		num=${part#*,}
		[ -f $id/method -a -f $id/format ] || continue
		# Formatting an EFI System Partition that already has a
		# filesystem on it is dangerous
		# (https://bugs.launchpad.net/bugs/769669).  The least bad
		# option seems to be to skip such partitions entirely.
		if [ -f $id/detected_filesystem ]; then
			continue
		fi
		method=$(cat $id/method)
		if [ "$method" = efi ]; then
			if [ -f $id/formatted ] && \
			   [ $id/formatted -nt $id/method ]; then
				continue
			fi
			log "Try to format EFI $new_efi_fs fs in $dev/$id"
			template=partman-basicfilesystems/progress_formatting
			open_dialog PARTITION_INFO $id
			read_line x1 x2 x3 x4 x5 device x6
			close_dialog

			RET=''
			db_metaget  partman/filesystem_short/efi description || RET=''
			[ "$RET" ] || RET=efi
			db_subst $template TYPE "$RET"
			db_subst $template PARTITION "$num"
			db_subst $template DEVICE $(humandev $(cat device))
			db_progress START 0 3 partman/text/formatting
			db_progress INFO $template
			db_progress SET 1
			log_sector_size="$(blockdev --getss "$(cat device)")"
			if [ "$log_sector_size" = 512 ]; then
				mkdosfs_opts=
			else
				# mkdosfs has trouble handling cluster
				# calculations for non-512-byte logical
				# sectors.  Forcing one sector per cluster
				# avoids this as long as the filesystem
				# isn't too large, but that shouldn't be a
				# problem for EFI System Partitions.
				mkdosfs_opts='-s 1'
			fi
			if log-output -t partman --pass-stdout \
			   $MKFS_FAT -F "${new_efi_fs#fat}" \
				     -S "$log_sector_size" \
				     $mkdosfs_opts \
				     "$device" >/dev/null; then
				sync
				status=OK
			else
				status=failed
			fi
			db_progress STOP

			if [ "$status" != OK ]; then
				db_subst partman-basicfilesystems/create_failed TYPE efi
				db_subst partman-basicfilesystems/create_failed PARTITION "$num"
				db_subst partman-basicfilesystems/create_failed DEVICE $(humandev $(cat device))
				db_input critical partman-basicfilesystems/create_failed || true
				db_go || true
				#disable_swap
				exit 1
			fi
			>$id/formatted
		fi
	done
done

#disable_swap
