#!/bin/sh

# Source: http://admincloud.net/116/creer-une-cle-usb-bootable-de-windows-sous-linux/

WIN_USB="${1}"
WIN_USB_MNT_PATH=/mnt/USBW7/
WIN_ISO_FILE="${2}"
WIN_ISO_MNT_PATH=/mnt/WIN7/
MS_SYS_VERSION="2.5.1"

# Test if args exists
for file in "${WIN_USB}" "${WIN_ISO_FILE}"; do
  if [ ! -e "${file}" ]; then
    printf '%b' "${file} doesn't exists. Please check your args.\n"
    exit 1
  fi
done

# Empty MBR
sudo dd if=/dev/zero of=${WIN_USB} bs=446 count=1

# Ensure to have a MS-DOS partition table
sudo parted ${WIN_USB} mklabel msdos

# Create one big partition with "boot" flag then format in NFTS
sudo parted ${WIN_USB} mkpart primary 0% 100%
sudo parted ${WIN_USB} set 1 boot on
#sudo mkfs.ntfs ${WIN_USB}1 --fast --no-indexing
# Need a FAT32 partition to be able to install Windaube on UEFI system!
sudo mkfs.vfat ${WIN_USB}1

# Mount first partition of the USB key
sudo mkdir -p -- "${WIN_USB_MNT_PATH}"
sudo mount ${WIN_USB}1 "${WIN_USB_MNT_PATH}"

# Mount ISO file
sudo mkdir -p -- "${WIN_ISO_MNT_PATH}"
sudo mount "${WIN_ISO_FILE}" "${WIN_ISO_MNT_PATH}" -o loop,ro

# Copy all files from ISO to USB
sudo cp -rv -- "${WIN_ISO_MNT_PATH}"* "${WIN_USB_MNT_PATH}"

# Umount and remove mount path
sudo umount "${WIN_USB_MNT_PATH}"
sudo umount "${WIN_ISO_MNT_PATH}"
sudo rmdir -- "${WIN_USB_MNT_PATH}" "${WIN_ISO_MNT_PATH}"

## Make the key bootable

# Ensure gettext is available
sudo aptitude install -y gettext

# Ensure to download the last version of ms-sys
if [ ! $(command -v ms-sys) ]; then
  # http://ms-sys.sourceforge.net/#Download
  wget http://netix.dl.sourceforge.net/project/ms-sys/ms-sys%20development/"${MS_SYS_VERSION}"/ms-sys-"${MS_SYS_VERSION}".tar.gz -O /tmp/ms-sys-"${MS_SYS_VERSION}".tar.gz

  # Extract and install ms-sys
  cd /tmp
  tar xzvf /tmp/ms-sys-"${MS_SYS_VERSION}".tar.gz
  cd /tmp/ms-sys-"${MS_SYS_VERSION}"
  sudo make
  sudo make install
fi

# For Win 7/8
sudo ms-sys --mbr7 "${WIN_USB}"

# For Win XP/2000/2003
#sudo ms-sys --mbr "${WIN_USB}"

# For Win Vista
#sudo ms-sys --mbrvista "${WIN_USB}"

exit 0
