#!/bin/sh

. /lib/partman/definitions.sh

dev=$1
num=$2
id=$3
size=$4
type=$5
fs=$6
path=$7
name=$8

cd $dev

[ -d $id ] || mkdir $id

if [ $fs = free -a -f $id/method ]; then
    rm $id/method
fi

if [ ! -f $id/method ]; then
    [ ! -f $id/acting_filesystem ] || rm $id/acting_filesystem
    >$id/available_filesystems
    exit 0
fi

method=$(cat $id/method)

if [ ! -f $id/use_filesystem ]; then
    property="$method"
elif [ -f $id/format ]; then
    property=formatable
else
    property=existing
fi

# sed can be removed here
filesystems=$(
    for i in /lib/partman/valid_filesystems/*; do
	if [ -x $i ]; then $i $dev $id "$property"; fi
    done | sed "s/${TAB}.*//"
)

available=''
for fs in $filesystems; do
    if [ "$fs" ]; then
	db_metaget partman/filesystem_long/$fs description || RET=''
	RET=${RET:-$fs}
	if [ "$available" ]; then
	    available="${available}${NL}${fs}${TAB}${RET}"
	else
	    available="${fs}${TAB}${RET}"
	fi
    fi
done

echo "$available" >$dev/$id/available_filesystems

# The outer echo removes the spaces
case $(echo $(echo "$available" | wc -l)) in
    0)
	if [ -f $id/acting_filesystem ]; then
	    rm $id/acting_filesystem
	fi
	;;
    1)
	echo ${available%$TAB*} >$id/acting_filesystem
	;;
    *)
	if [ -f $id/filesystem ]; then
	    cp $id/filesystem $id/acting_filesystem
	else
	    if [ -f $id/acting_filesystem ]; then
		rm $id/acting_filesystem
	    fi
	fi
	;;
esac


open_dialog PARTITION_INFO $id
read_line num id size type fs path name
close_dialog

if
    [ -f $dev/$id/acting_filesystem ] \
	&& new_acting=$(cat $dev/$id/acting_filesystem) \
	&& [ -f /lib/partman/parted_names/$new_acting ] \
	&& new_fs=$(cat /lib/partman/parted_names/$new_acting) \
	&& [ "$fs" != "$new_fs" ]
then
    open_dialog CHANGE_FILE_SYSTEM $id $new_fs
    close_dialog
fi
