#!/bin/bash
IMG_TYPE=${IMG_TYPE:-qcow2}
SIZE=${SIZE:-20000} # MiB

HLP() {
    cat <<EOF
Usage: $0 [OPTIONS] ISO_FILE

Options:
  -t, --image-type TYPE   Image type (qcow2, img, etc.) (default: qcow2)
  -s, --size SIZE         Image size in MiB (default: 20000)
  -h, --help              Show this help message and exit

Example:
  $0 -t qcow2 -s 15000 ubuntu-20.04.iso
EOF
    exit 0
}

echo_exit() {
    clear
    echo "ERROR: line: $@" 1>&2
    echo ':(' 1>&2
    exit $1
}

clear(){
  echo "==> Clear" 1>&2
  qemu-nbd --disconnect /dev/nbd0
}

mk_img(){
  echo "==> mk_img" 1>&2
  if [ "$IMG_TYPE" != 'img' ] ; then
    qemu-img create -f "$IMG_TYPE" "$1" "${SIZE}M"
  else
    dd if=/dev/zero of="$1" bs=1 count=0 seek="${SIZE}M"
  fi
}

connect_img() {
  echo "==> connect_img" 1>&2
  if [ $IMG_TYPE != img ] ; then
    if qemu-nbd --connect=/dev/nbd0 $(realpath $1) 1>&2 ; then
      echo /dev/nbd0
    else
      echo_exit ${LINENO} "Cannot connect /dev/nbd"
    fi
  else
    blk=$(losetup -f)
    if losetup $blk $(realpath $1) ; then
      echo "$blk"
    else
      echo_exit ${LINENO} "losetup error"
    fi
  fi
}

while [ -n "$1" ] ; do
  case "$1" in
    "-t" | "--image-type" ) shift
           IMG_TYPE=$1;;
    "-s" | "--size" ) shift
           SIZE=$1;;
    "-h" | "--help" ) HLP;;
    *) ISO=$(realpath $1) ;;
  esac
  shift
done

if [ $(id -un) != root ] ; then
  echo "need root"
  exit ${LINENO}
elif ! [ -f "$ISO" ] ; then
  echo $ISO
  HLP
fi

IMG=$(realpath "$(basename $ISO |sed 's/.iso$//')".$IMG_TYPE)
command -v qemu-img || echo_exit ${LINENO} "qemu-img comman not found"
modprobe nbd max_part=8 || echo_exit ${LINENO} "Cannot insert nbd kernel module"
clear
trap 'clear' EXIT
mk_img "$IMG"
blkdev=$(connect_img "$IMG")
echo "dd if="$ISO" of="$blkdev" bs=4M"
dd if="$ISO" of="$blkdev" bs=4M
