#!/bin/sh
# Detects all Microsoft OSes on a collection of partitions.

. /usr/share/os-prober/common.sh

partition=$1
mpoint=$2
type=$3

# Weed out stuff that doesn't apply to us
case "$type" in
	ntfs|ntfs-3g) debug "$1 is a NTFS partition" ;;
	vfat) debug "$1 is a FAT32 partition" ;;
	msdos) debug "$1 is a FAT16 partition" ;;
	fuse|fuseblk) debug "$1 is a FUSE partition" ;; # might be ntfs-3g
	*) debug "$1 is not a MS partition: exiting"; exit 1 ;;
esac

# Vista/Longhorn
if item_in_dir -q bootmgr "$2" && item_in_dir -q boot "$2" &&
   item_in_dir -q bcd $2/$(item_in_dir boot "$2"); then
	long="Windows Vista/Longhorn (loader)"
	short=Windows
# 2000/XP/NT4.0
elif item_in_dir -q ntldr "$2" && item_in_dir -q ntdetect.com "$2"; then
	long="Windows NT/2000/XP"
	short=Windows
	ini=$(item_in_dir boot.ini "$2")
	if [ -n "$ini" ]; then
		multicount="$(grep -e "^multi" "$2/$ini" | wc -l)"
		scsicount="$(grep -e "^scsi" "$2/$ini" | wc -l)"
		msoscount="$(expr ${multicount} + ${scsicount})"
		if [ $msoscount -eq 1 ]; then
			# We need to remove a Carriage Return at the end of
			# the line...
			defaultmspart="$(grep -e "^default=" "$2/$ini" | cut -d '=' -f2 | tr -d '\r')"
			# Escape any backslashes in defaultmspart
			grepexp="^$(echo $defaultmspart | sed -e 's/\\/\\\\/')="
			# Colons not allowed; replace by spaces
			# Accented characters (non UTF-8) cause debconf to
			# hang, so we fall back to the default if the name
			# contains any weird characters.
			long="$(grep -e "$grepexp" "$2/$ini" | cut -d '"' -f2 | \
				tr ':' ' ' | grep -v '[^a-zA-Z0-9 &()/_-]')"
			if [ -z "$long" ]; then
				long="Windows NT/2000/XP"
			fi
		else
			long="Windows NT/2000/XP (loader)"
		fi
	fi
# MS-DOS
elif [ -d "$(item_in_dir dos $2)" ]; then
	long="MS-DOS 5.x/6.x/Win3.1"
	short=MS-DOS
# 95/98/Me
elif item_in_dir -q windows "$2" &&
     item_in_dir -q win.com $2/$(item_in_dir windows "$2"); then
	long="Windows 95/98/Me"
	short=Windows9xMe
else
	exit 1
fi

label=$(count_next_label $short)
result "${partition}:${long}:${label}:chain"
exit 0
