#!/bin/sh

if [ "$1" = "--detached" ]; then
  shift
else
  [ -x "$0" ] || chmod +x "$0"
  "$0" --detached ${1+"$@"} &
  wait $!
  exit $?
fi

source /etc/preinit
script_init

getCmdLine(){
  dd status=none "if=$1" bs=64 count=8 skip=1 | tr -d '\0' | tr ' ' '\n'
  echo
}

validBoot2f(){
  [ -f "$1" ] || return 1
  sntool check "$1" >/dev/null && return 0
  echo "invalid image: $1" 1>&2
  return 1
}

memboot(){
  local bootimg="$1";shift
  validBoot2f "$bootimg" || return 1
  local mbHost=""; [ "$(usbMode)" = "host" ] && mbHost="$modname-usb-host"
  local cmdline="$(getCmdLine "$bootimg" | (grep -v "$modname-*shell"; echo "$@"; echo "$modname-chainload $mbHost") | xargs)"
  echo "memboot $bootimg $cmdline"
  kexec -l -t zImage "$bootimg" "--command-line=$cmdline" --atags || return 1
  trap ":" HUP TERM
  killall -q clovershell
  service inetd stop
  uistop
  sync
  cd /
  umount -a -r 2>/dev/null
  exec >/dev/null 2>&1
  disableUsbDevice
  kexec -e
  while :;do sleep 1;:;done
}

reboot_kexec(){
  local bootimg="$1"
  if [ -f "$bootimg" ]; then
    shift
  else
    bootimg="$rootfs/boot/boot.img"
    [ -f "$bootimg" ] || bootimg="$installpath/boot/boot.img"
    if [ ! -f "$bootimg" ]; then
      bootimg="$temppath/boot.img"
      readBoot2 > "$bootimg" || return 1
    fi
  fi
  memboot "$bootimg" ${1+"$@"}
}

clovershellActive(){
  [ "$cf_clovershell" = "y" ] && return 0
  (ps | grep -vF grep;pack_list) | grep -qF clovershell
}

recovery(){
  local bootimg="$1"
  [ -f "$bootimg" ] && shift || bootimg=""
  local rshell="$modname-shell"
  clovershellActive && rshell="$modname-clovershell"
  echo "$*" | grep -q "$modname-*shell" && rshell=""
  reboot_kexec "$bootimg" "$rshell" ${1+"$@"}
}

cdir="$(dirname "$(readlink -f "$0")")"
if [ -f "$cdir/kexec" ]; then
  [ -x "$cdir/kexec" ] || chmod +x "$cdir/kexec"
  export PATH="$cdir:$PATH"
fi
${1+"$@"}
