#!/bin/bash

set -e

START_DIR_DONT_CHANGE=`pwd`
SELF=$(basename "$0")
# required config items
RELENG_XORRISO=""
RELENG_DIR=""
RELENG_IMG=""
# optional config items
RELENG_ISOLINUX_BIN=""
RELENG_BOOT_CAT=""
CONFFILE=$HOME/.libburnia-releng/releng_build_isojigdo.conf
KEEP=0
GEN_DATA_DIR=releng_generated_data/${SELF}
RES=""

print_help() {
 cat << HLP
Usage:
 ${SELF} -help

# using a config file ${CONFFILE}
 ${SELF} -rc [-keep]

# without using a config file
 ${SELF} xorriso_cmd IN_dir OUT_image [IN_isolinux] [OUT_bootcat] [-keep]

# cleanup test generated data directory and exit
 ${SELF} -cleanup
HLP
}

#####################################################################
# cleanup
if [ "${1}" == "-cleanup" ]; then
 cd "${START_DIR_DONT_CHANGE}" || exit 80
 if [ -d "${GEN_DATA_DIR}" ]; then
    rm -rf ${GEN_DATA_DIR}
    printf "${SELF}: removed %s\n" ${GEN_DATA_DIR}
 else
    printf "${SELF}: ${GEN_DATA_DIR} does not exist.\n"
 fi
 exit 0
fi

# help
if [ ! "${1}" ]; then print_help && exit 10; fi
# config file
if [ "${1}" == "-rc" ]; then
 if [ -e ${CONFFILE} ]; then
  . ${CONFFILE}
  printf "${SELF}: Using config file %s\n" ${CONFFILE}
 else
  echo -e "\n${SELF}: Config file ${CONFFILE} not found.\n" && exit 20
 fi
 if [ "${2}" == "-keep" ]; then KEEP=1; fi
# command line args
elif [ "${3}" ]; then
 RELENG_XORRISO="${1}"
 RELENG_DIR="${2}"
 RELENG_IMG="${3}"
 if [ "${4}" ]; then
  RELENG_ISOLINUX_BIN="${4}"
  if [ "${5}" ]; then RELENG_BOOT_CAT="${5}"; fi
  if [ "${4}" == "-keep" -o "${5}" == "-keep" -o "${6}" == "-keep" ]; then KEEP=1; fi
 fi
# the rest
else
 print_help && exit 30
fi

# data dir
if [ -d "${GEN_DATA_DIR}" ]; then
 printf "\n${SELF}: directory %s exists!" ${GEN_DATA_DIR}
 printf "\n${SELF}: use '${SELF} -cleanup' to remove.\n"
 exit 2
else
 mkdir "${GEN_DATA_DIR}"
fi

if [ "${RELENG_XORRISO}" == "" -o "${RELENG_DIR}" == "" -o "${RELENG_IMG}" == "" ]; then
 echo -e "\n${SELF}: xorriso_cmd IN_dir and OUT_image are required\n"
 exit 40
fi

if [ ! -x "${RELENG_XORRISO}" ]; then
 printf "${SELF}: Not found or not an executable: $RELENG_XORRISO\n"
 exit 50
fi

# all must be set at this point
printf "${SELF}: Config items:"
printf "\n\txorriso_cmd=${RELENG_XORRISO}\n\tIN_dir=${RELENG_DIR}\n\tOUT_image=${RELENG_IMG}.iso"
printf "\n\tIN_isolinux=${RELENG_ISOLINUX_BIN}\n\tOUT_bootcat=${RELENG_BOOT_CAT}\n"
RES="${RELENG_IMG}.iso ${RELENG_IMG}.new ${RELENG_IMG}.md5 ${RELENG_IMG}.jigdo ${RELENG_IMG}.template"

# xorriso version details, incl. underlying libraries
"${RELENG_XORRISO}" -version
if ! "${RELENG_XORRISO}" -version | grep libjte >/dev/null 2>&1; then
 printf "\n${SELF}: JTE not supported with this xorriso build. Install jigit and rebuild."
 printf "\n${SELF}: See http://www.einval.com/~steve/software/JTE/\n"
 exit 51
fi

# remove cruft from previous runs
# rm -f ${RES}

# grab an MBR
# dd if=some.iso bs=1K count=32 of=somembr.sysarea

# create FAT partition
# /sbin/mkfs.msdos -n Bla -C fatpart.fat 8192

# create MD5 list in base64 format
if which jigdo-gen-md5-list >/dev/null 2>&1; then
 printf "${SELF}: Creating MD5 list in hex format..."
 jigdo-gen-md5-list ${RELENG_DIR} > ${GEN_DATA_DIR}/${RELENG_IMG}.md5
 printf "Done.\n"
else
 printf "\n${SELF}: Not found: jigdo-gen-md5-list. Install jigit."
 printf "\n${SELF}: See http://www.einval.com/~steve/software/JTE/\n"
 exit 60
fi

# build the command - general section
CMD="${RELENG_XORRISO} \
 -as mkisofs \
 -quiet \
 -o ${GEN_DATA_DIR}/${RELENG_IMG}.iso \
 -R \
 -V ISOJIGDO \
 -partition_offset 16 \
 -J -joliet-long \
"

# boot section TODO
#if [ "${RELENG_ISOLINUX_BIN}" -a "${RELENG_BOOT_CAT}" ]; then
#CMD+=\
# -b ${RELENG_ISOLINUX_BIN} \                         # NOTE: boot/isolinux/isolinux.bin
# -c ${RELENG_BOOT_CAT} \                             # NOTE: boot/boot.cat
# -no-emul-boot -boot-load-size 4 -boot-info-table \
# -isohybrid-mbr somembr.sysarea \                    # TODO: figure out where to grab one
# -partition_offset 16 \
# -append_partition 2 0x01 fatpart.fat \              # TODO: create one unconditionally?
#fi

# jigdo section
CMD+="\
 -jigdo-template-compress gzip \
 -checksum_algorithm_iso md5,sha1,sha256,sha512 \
 -checksum_algorithm_template md5,sha1,sha256,sha512 \
 -jigdo-jigdo ${GEN_DATA_DIR}/${RELENG_IMG}.jigdo \
 -jigdo-template ${GEN_DATA_DIR}/${RELENG_IMG}.template \
 -jigdo-map Debian=${RELENG_DIR} \
 -md5-list  ${GEN_DATA_DIR}/${RELENG_IMG}.md5 \
 -jigdo-min-file-size 1024 \
"

CMD+="${RELENG_DIR}"

# run it
echo -e "${SELF}: Creating ISO and jigdo representations:\n$CMD\n"
${CMD}

# create another one from jigdo files
if which jigit-mkimage >/dev/null 2>&1; then
 printf "${SELF}: Creating new ISO from jigdo files..."
 jigit-mkimage \
  -t ${GEN_DATA_DIR}/${RELENG_IMG}.template \
  -j ${GEN_DATA_DIR}/${RELENG_IMG}.jigdo \
  -m Debian=${RELENG_DIR} \
  -o ${GEN_DATA_DIR}/${RELENG_IMG}.new
 printf "Done.\n"
else
 printf "\n${SELF}: Not found: jigit-mkimage. Install jigit."
 printf "\n${SELF}: See http://www.einval.com/~steve/software/JTE/\n"
 exit 70
fi

# trap the exit code of diff and let the Universe explode
diff ${GEN_DATA_DIR}/${RELENG_IMG}.iso ${GEN_DATA_DIR}/${RELENG_IMG}.new
DIFF_RET="$?"
case ${DIFF_RET} in
     0)
      echo -e "${SELF}: diff ${GEN_DATA_DIR}/${RELENG_IMG}.iso ${GEN_DATA_DIR}/${RELENG_IMG}.new matched.\n"
     ;;
     *)
      echo -e "${SELF}: FAIL: diff returned code: $DIFF_RET\n"
     ;;
esac

# sort out the cruft
if [ ${KEEP} -eq 0 ]; then
 # safety net, just in case -> we want to be in the starting
 # directory before removing whatever self-generated stuff
 cd "${START_DIR_DONT_CHANGE}" || exit 80
 rm -rf ${GEN_DATA_DIR}
 printf "${SELF}: removed %s\n" ${GEN_DATA_DIR}
else
 printf "${SELF}: leaving %s\n" ${GEN_DATA_DIR}
fi

# last hints
printf "\n${SELF}: HINT: manual checks remained to be done:\n"
printf " * ${RELENG_IMG}.img boots from USB stick and/or optical media.\n"
printf " * appended FAT partition is mountable.\n"
printf " * xorriso -indev ${RELENG_IMG}.iso -pvd_info\n"
printf " * fdisk -lu ${RELENG_IMG}.iso\n"

exit 0