source "$modpath/script/install"

backup_nandc
mount_base
backup

source_config

local transferpath="$modpath/transfer"

cd "$transferpath"

[ -f "$transferpath/earlybird" ] && source "$transferpath/earlybird"
rm -f "$transferpath/earlybird"

if [ -d "$transferpath/reflash" ]; then
  cd "$transferpath/reflash"
  source "$modpath/script/reflash"
  cd "$transferpath"
  rm -rf "$transferpath/reflash"
fi

# transfer firmware, if any
if [ -d "$transferpath/firmware" ]; then
  local firmware="$(find "$transferpath/firmware" -type f -name "*.hsqs" | sort | head -n 1)"
  if [ -f "$firmware" ]; then
    mkdir -p "$firmwarepath"
    local firmware_name="$(basename "$firmware")"
    find "$firmwarepath" -type f -not -name "$firmware_name" -delete
    echo "transferring firmware..."
    copy "$firmware" "$firmwarepath/"
  fi
  rm -rf "$transferpath/firmware"
fi

# if we're running modified firmware, mount it now
source_parts "$modpath/rootfs/etc/preinit.d/p????_*firmware*"

# now we can do install/repair
if [ -f "$preinit" ]; then
  echo "$modname already installed"
  mod_repair
else
  mod_install
fi

[ -f "$transferpath/uninstall" ] && packs_uninstall $(cat "$transferpath/uninstall")
rm -f "$transferpath/uninstall"
[ -f "$transferpath/hmod/uninstall" ] && packs_uninstall $(cat "$transferpath/hmod/uninstall")
rm -f "$transferpath/hmod/uninstall"

packs_install "$transferpath"
if [ -d "$transferpath/hmod" ]; then
  packs_install "$transferpath/hmod"
  rm -rf "$transferpath/hmod"
fi

if [ -d "$transferpath/games" ]; then
  source "$modpath/script/games"
  transfer_games "$transferpath/games"
  rm -rf "$transferpath/games"
fi

echo "transferring data..."
transfer_path "$transferpath"
echo

save_config
[ "$cf_shutdown" != "y" ] || shutdown
echo
