#!/bin/bash

_BASE_DIR_=$(readlink -f $(dirname "${BASH_SOURCE[0]}"))
# load config
_CONFIG_FILE_=${_BASE_DIR_}/config

. ${_CONFIG_FILE_}

# check remaster directory exists
if [ ! -d "${_REMASTER_DIR_}" ] ; then
  echo 'directory missing: '${_REMASTER_DIR_} >&2
  exit 1
fi

cd "${_REMASTER_DIR_}" || exit 1

if [ ! -e "${_ISO_SRC_PATH_}" ] ; then
  echo 'missing source iso: '${_ISO_SRC_PATH_} >&2
  exit 1
fi

if [ -e "${_ISO_OUT_PATH_}" ] ; then
  echo 'iso destination file already exists: '${_ISO_OUT_PATH_} >&2
  exit 1
fi

_ISO_VOLUME_ID_LENGTH_=${#_ISO_VOLUME_ID_}

if [ ${_ISO_VOLUME_ID_LENGTH_} -gt 32 ] ; then
  echo 'iso volume id length exceeded (max 32 characters): '"'${_ISO_VOLUME_ID_:0:32}'" >&2
  exit 1
fi

if [ ${_ISO_VOLUME_ID_LENGTH_} -lt 1 ] ; then
  echo 'iso volume id missing' >&2
  exit 1
fi

echo -en 'creating checksum file ... '

md5sum `find ! -name 'md5sum.txt' ! -path './isolinux/*' -follow -type f` > md5sum.txt
_RETURN_=$?

if [ ${_RETURN_} -ne 0 ] ; then
  echo 'failed to create checksum file' >&2
  exit 1
fi

echo 'done'

xorriso -as mkisofs -r -z \
  -V "${_ISO_VOLUME_ID_}" \
  -o "${_ISO_OUT_PATH_}" \
  --modification-date="$(date +%Y%m%d%H%M%S00)" \
  -isohybrid-mbr --interval:local_fs:0s-15s:zero_mbrpt,zero_gpt,zero_apm:"${_ISO_SRC_PATH_}" \
  -partition_cyl_align on \
  -partition_offset 0 \
  -partition_hd_cyl 64 \
  -partition_sec_hd 32 \
  --mbr-force-bootable \
  -apm-block-size 2048 \
  -iso_mbr_part_type 0x00 \
  -c '/isolinux/boot.cat' \
  -b '/isolinux/isolinux.bin' \
  -no-emul-boot \
  -boot-load-size 4 \
  -boot-info-table \
  -eltorito-alt-boot \
  -e '/boot/grub/efi.img' \
  -no-emul-boot \
  -boot-load-size 18976 \
  -isohybrid-gpt-basdat \
  -isohybrid-apm-hfsplus \
  .

_RETURN_=$?

if [ ${_RETURN_} -ne 0 ] ; then
  echo 'failed to create: '${_ISO_OUT_PATH_} >&2

  if [ -e "${_ISO_OUT_PATH_}" ] ; then
    rm "${_ISO_OUT_PATH_}"
  fi

  exit ${_RETURN_}
fi

echo 'ISO file created: '${_ISO_OUT_FILE_}

cd "${_ISO_OUT_PATH_%/*}" || exit 1

_ISO_HASH_FILE_="${_ISO_OUT_FILE_}.sha512"

shasum -a 512 "${_ISO_OUT_FILE_}" > "${_ISO_HASH_FILE_}"

echo 'HASH file created: '${_ISO_HASH_FILE_}

