#!/bin/bash
DST=""

while getopts ":d:" opt; do
  case ${opt} in
    d )
      DST=$OPTARG
      ;;
    \? )
      echo "Invalid option: $OPTARG" 1>&2
      ;;
    : )
      echo "Invalid option: $OPTARG requires an argument" 1>&2
      ;;
  esac
done

if [ -b "${DST}" ]; then
  echo "Found block device: ${DST}"
  read -p "Press any key to continue... "
else
  print "${DST} does not exist or is not a block device."
  exit 1
fi

echo "${DST}" | grep "nvme"
EXIT_CODE=$?
PREFIX=""

if [ $EXIT_CODE == "0" ]; then
  PREFIX="p"
fi


curl -n ~/.netrc \
--silent http://nfs-netboot.engr.unr.edu/images/base/parts.table | \
sfdisk --force "${DST}"

sync

hdparm -z ${DST}


echo "Partiton 1: WinRE"
#Partition 1
if [ -b "${DST}${PREFIX}1" ]; then
  echo "Found partition: ${DST}${PREFIX}1"
  curl -n ~/.netrc \
  --silent http://nfs-netboot.engr.unr.edu/images/base/1.part | \
  dd of="${DST}${PREFIX}1" status=progress
else
  print "${DST}${PREFIX}1 not found"
  exit 1
fi


echo "Partiton 2: EFI"
#Partition 2
if [ -b "${DST}${PREFIX}2" ]; then
  echo "Found partition: ${DST}${PREFIX}2"
  curl -n ~/.netrc "user:ember19" \
  --silent http://nfs-netboot.engr.unr.edu/images/base/2.part | \
  dd of="${DST}${PREFIX}2" status=progress
else
  print "${DST}${PREFIX}2 not found"
  exit 1
fi


echo "Partiton 3: Reserved"
#Partition 3
if [ -b "${DST}${PREFIX}3" ]; then
  echo "Found partition: ${DST}${PREFIX}3"
  curl -n ~/.netrc \
  --silent http://nfs-netboot.engr.unr.edu/images/base/3.part | \
  dd of="${DST}${PREFIX}3" status=progress
else
  print "${DST}${PREFIX}3 not found"
  exit 1
fi


echo "Partiton 4: Root filesystem"

#Partition 4
if [ -b "${DST}${PREFIX}4" ]; then
  echo "Found partition: ${DST}${PREFIX}4"
  curl -n ~/.netrc \
  --silent http://nfs-netboot.engr.unr.edu/images/base/4.part.zst | \
  zstd --long=31 -T4 -d --stdout -q | \
  ntfsclone --restore-image --overwrite "${DST}${PREFIX}4" -

else
  print "${DST}${PREFIX}4 not found"
  exit 1
fi

exit 0
