#!/bin/ash
#
# sourced by init  -- sets ISO_LOOP
#
# - sets PMEDIA=cd
# - sets PSUBDIR=""
# - sets ISO_PSAVE
#
# requires: wait_for_usb() get_part_info() check_status()
#           decode_id()
#           ensure_mounted()
#
# loopback.cfg
# - https://askubuntu.com/questions/644400/is-there-documentation-for-iso-scan-filename
# - https://packages.ubuntu.com/disco/lupin-casper
#
# find_iso = iso-scan/filename

# A proper shutdown is achieved if:
# - sfs's are copied to ram
# - a savefolder is used

#===================
#    grub4dos  
#===================
#title Start pup.iso
#  find --set-root --ignore-floppies /ISO/pup.iso
#  map /ISO/pup.iso (0xff)
#  map --hook
#  root (0xff)
#  kernel (0xff)/vmlinuz find_iso=/ISO/pup.iso
#  initrd (0xff)/initrd.gz

#===================
#      grub2
#===================
#menuentry "Start pup.iso" {
#    set isofile="/ISO/pup.iso"
#    loopback loop $isofile
#    set root=(loop)
#    linux    (loop)/vmlinuz find_iso=$isofile
#    initrd   (loop)/initrd.gz
#}

#==================================================

iso_path=

if [ "$isofrom" ] ; then
  iso_path="$isofrom"
fi

if [ "$img_loop" ] ; then
  iso_path="$img_loop"
fi

if [ "$isoloop" ] ; then
  iso_path="$isoloop"
fi

if [ "$findiso" ] ; then
  iso_path="$findiso"
fi

if [ "$find_iso" ] ; then
  iso_path="$find_iso"
fi

if ! [ "$iso_path" ] ; then
  for x in $(cat /proc/cmdline); do
    case ${x} in
      iso-scan/filename=*) iso_path=${x#iso-scan/filename=} ;;
    esac
  done
fi

#==================================================

if [ "$iso_path" ]; then

  PMEDIA=cd
  FOUND_ISO=
  wait_for_usb

  for ONETRY in $HAVE_PARTS
  do
    ONE_PART="$(echo -n "$ONETRY" | cut -f 1 -d '|')"
    ensure_mounted "$ONE_PART" "/mnt/dev_save"
    if [ "$ONE_MP" ];then
      if [ -f "/mnt/dev_save/${iso_path#/}" ]; then
        ISO_PSAVE=${ONE_PART}
        ISO_PSAVE_FS=$(blkid /dev/${ISO_PSAVE} | grep -o ' TYPE=".*' | cut -f 2 -d '"')
        FOUND_ISO=/mnt/dev_save/${iso_path#/}
        break
      fi
      umount $ONE_MP
    fi
  done

  if ! [ "$FOUND_ISO" ] ; then
    echo -en "\n Could not find the ISO $iso_path \n "
    exec /bin/sh >/dev/console 2>&1
  fi

  ISO_LOOP=$(losetup -f)
  if losetup $ISO_LOOP "$FOUND_ISO" ; then
    PSUBDIR=""
  else
    echo -en "\n Error mounting ISO $iso_path \n "
    exec /bin/sh >/dev/console 2>&1
  fi

fi

