#!/bin/sh
# gpg signed by build@mfd-gw-aklnz at @1770430808.
# Update script

# System handshake magic
CODENAMELIST=norris:mx6,lisa:mx6
DATESTAMP=20251217062101
PERSIST_LANG_DISABLE=
TARGET_LANGUAGE_PACK=standard
S5100_UPD_PAYLOAD=
UNAME=armv7l
UPD_FLAGS=A

# This progress bar delay is just used as an approximate speed for moving the progress bar
# After the bar has passed 75%, it will slow to 1/2 this rate, and 1/4 this rate after 90%
PROGRESSBARDELAY=1

# Print out the updater version. This needed by the factory to validate the correct version is being
# programmed when doing automated CPU card programming
# NOTE: makeupd.sh will modify this line
echo UPDATEVERSION=NSS_evo3-26.1-72.1.28-38.6-8-gc227e2914

# TODO: Detect need for UBI repair automatically. This should only ever need to be done once
#       at the factory. Probably use logic of if (!ubiattach) || (volumecount != 3) { ubirepair }

DEBUG=${DEBUG:-false}
if [ -e /dev/shm/debug ]; then
   DEBUG=true
fi
${DEBUG} && set -x

# If anything goes awry, exit early.
set -e

# We expect to be invoked from the /tmp directory.
# We expect to have working /proc and /sys directories, as well as a populated /dev

### This upgrade script expects the following environment variables to be present:
# UPDFILE -- a path to the '.upd' update file.
#    ex:  UPDFILE = /path/to/foo.upd
#    This file path is found during the discovery phase of the initramfs
#    and will be relative to the ramfs root.
if [ -z "${UPDFILE}" ]; then
   echo "Internal error: Bad environment.  UPDFILE was not set."
   exit 1;
fi

# HFP-1245: Insert template code from scripts/update_common.sh
find_component_sha1() {
    local ref_sha1="$(
    grep -A 100 "^###SHA1MAGIC###$" "${SHA1MAGIC_SRC:-${0}}" | \
    grep -o "[^ ]\{${SHA1SIZE:-40}\}  ${1}$"
    )"

    if [ $? -ne 0 -o -z "$ref_sha1" ]; then
    printf 'File "%s" not found in internal hash table.\n' "${1}" >&2
    return 1
    fi

    echo "$ref_sha1" | cut -f 1 -d ' '
}

sha1check() {
    local sha1cmd=${SHA1CMD:-sha1sum} external=0

    if [ "${1}" = "-external" ]; then
    external=1
    shift 1
    fi

    local file="${1}"
    local act_sha1 ref_sha1=$(find_component_sha1 "$file")

    if [ -z "$ref_sha1" ]; then
    # Error message printed by find_component_sha1()
    return 1
    fi

    [ "$DEBUG" = true ] && printf 'Stored SHA1 for "%s" is %s\n' "$file" "$ref_sha1" >&2

    local f_copy
    [ -d "${SHA1CHECK_SAVEDIR:-}" ] && f_copy="${SHA1CHECK_SAVEDIR}/${file}"

    if [ $external = 1 ]; then
    act_sha1="$(cat "$(dirname "${UPDFILE}")/${file}"            | tee ${f_copy+"$f_copy"} | $sha1cmd | cut -f 1 -d ' ')"
else
    act_sha1="$(tar -xOf "${UPDFILE}" ${COMPONENT_PREFIX:-}${file} | tee ${f_copy+"$f_copy"} | $sha1cmd | cut -f 1 -d ' ')"
    fi

    [ "$DEBUG" = true ] && printf 'Calculated SHA1 for "%s" is %s\n' "$file" "$act_sha1" >&2

    if [ "${ref_sha1}" != "${act_sha1}" ]; then
    printf 'ERROR: Update corrupt.  File "%s" failed checksum.\n' "$file"
    printf 'Please delete this update and replace it with a new copy.\n'
    return 1
else
    [ "$DEBUG" = true ] && printf 'DEBUG: successful sha1sum check: %s\n' "$file" >&2
    return 0
    fi
}

sha1check libupdate.sh || exit 1

tar -xOf "${UPDFILE}" "${COMPONENT_PREFIX:-}"libupdate.sh > libupdate.sh

. ./libupdate.sh



# HFP-2392: Fix Vulcan series, Zeus2 and Muriwai devices manufactured without U-boot CODENAME override set.
case "${THISCODENAME}:${CODENAMELIST}" in
"cassius:cassius:mx6,lubeck:mx6"|"floyd:floyd:mx6,floydbandg:mx6"|"floydjr:floydjr:mx6,vulcanjr:mx6"|"floydfs:floydfs:mx6,vulcanfs:mx6")
    SPLASHY_OVERRIDE=bandg
    FIXUP_CODENAME=true
    ;;
"hatchetfish:hatchetfish:mx6,muriwai:mx6")
    SPLASHY_OVERRIDE=muriwai
    FIXUP_CODENAME=true
    ;;
"cassius:cassius:mx6,penn:mx6")
    SPLASHY_OVERRIDE=mercury
    FIXUP_CODENAME=true
    ;;
esac

if [ -n "${SPLASHY_OVERRIDE:-}" ]; then
    ln -sf /etc/splashy_${SPLASHY_OVERRIDE} /etc/splashy
fi

start_splashy

#show_debug_msg

splashy_update "print Preparing update..."

DISPLAYRES=$(display_res)
NANDGEOMETRY=$(nand_geometry)
NANDSIZE=$(nand_size)

echo $DISPLAYRES $NANDGEOMETRY $NANDSIZE
have_emmc && echo eMMC Detected

# HFP-2392: Fix Vulcan series, Zeus2 and Muriwai devices manufactured without U-boot CODENAME override set.
if [ -n "${FIXUP_CODENAME:-}" ]; then
    if mount -t ubifs -o ro ubi0:NOS /mnt; then
        case "$(grep -is -m1 "^ProductId=" "/mnt/Config.ini" | cut -d= -sf2 | tr -d '\r' | tr '[:upper:]' '[:lower:]')" in
        zeus2wm) CONVCODENAME=lubeck ;;
        muriwai) CONVCODENAME=muriwai ;;
        vulcan7) CONVCODENAME=floydbandg ;;
        vulcanfs) CONVCODENAME=vulcanfs ;;
        vulcanjr) CONVCODENAME=vulcanjr ;;
        penn|vv702) CONVCODENAME=penn ;;
        esac

        umount /mnt
    fi

    if [ -z "${CONVCODENAME:-}" ]; then
        log_update_failure
        echo "ERROR: This update is not suitable for this device."
        splashy_update "print This update is not suitable for this device.
Remove SD card to reboot."
        wait_for_media
        splashy_update "exit"
        reboot -f
    fi
fi

###  Prepare early tools.
# None for now

echo "Showing 'validating update' notification."
splashy_update "print Validating update. Please wait...
Do not turn off during update, as
this may damage your device."

start_progress_bar

if find_component_sha1 simulator.tar.gz; then
  HAVE_SIM_PAYLOAD=true
  validate_component simulator.tar.gz || corrupt_component_fail simulator
else
  HAVE_SIM_PAYLOAD=false
fi

if [ "${FAMILY_NAME}" = "Hatchetfish" ] && [ "${THISCODENAME}" = "thor" ] && hf-sync is_cpu_a; then
  ROOT_PAYLOAD="root-thor.tar.xz"
  if find_component_sha1 usr-thor.img.xz; then
    USR_PAYLOAD="usr-thor.img.xz"
  else
    USR_PAYLOAD="usr-thor.tar.xz"
  fi
else
  ROOT_PAYLOAD="root.tar.xz"
  # FloydSr and FloydRw use the same standard updater and have both usr.tar.xz and usr.img.xz as usr payload
  # Choose the correct one by having emmc or not
  if have_emmc && find_component_sha1 usr.img.xz; then
    USR_PAYLOAD="usr.img.xz"
  else
    USR_PAYLOAD="usr.tar.xz"
  fi
fi

FACTORYDATA_OVERLAY_PAYLOAD=factorydata-overlay.tar.xz
if find_component_sha1 "$FACTORYDATA_OVERLAY_PAYLOAD"; then
    validate_component "$FACTORYDATA_OVERLAY_PAYLOAD" || corrupt_component_fail factorydata-overlay
else
    FACTORYDATA_OVERLAY_PAYLOAD=
fi

# Check for persistent languages
for i in standard easterneuropean russianukrainian middleeastern asian; do
    if find_component_sha1 "$i".tar.xz; then
        validate_component "$i".tar.xz || corrupt_component_fail "language pack $i"
        LANGUAGE_PACKS="$LANGUAGE_PACKS $i"
    fi
done

factorydata_directory=/mnt/media/factorydata
# HFP-1774: Any mount point could be corrupted in this block, need explicit checking.
if [ -n "$LANGUAGE_PACKS" ];then
    HAVE_LANGUAGE_PACKS=true
    temp_conf_dir=/tmp/persistent_languages
    mkdir -p "$temp_conf_dir"
    if mount -t ubifs -o ro ubi0:NOS "$temp_conf_dir"; then
        if [ -d "$temp_conf_dir"/features ]; then
            for FEATURE_FILE in $(ls "$temp_conf_dir"/features); do
                if [ "$FEATURE_FILE" -gt 128 -a "$FEATURE_FILE" -lt 133 ]; then
                    case "$FEATURE_FILE" in
                        129) # Feature code: AA55CC81
                            REQUESTED_LANGUAGE_PACK="easterneuropean"
                            ;;
                        130) # Feature code: AA55CC82
                            REQUESTED_LANGUAGE_PACK="russianukrainian"
                            ;;
                        131) # Feature code: AA55CC83
                            REQUESTED_LANGUAGE_PACK="middleeastern"
                            ;;
                        132) # Feature code: AA55CC84
                            REQUESTED_LANGUAGE_PACK="asian"
                            ;;
                        *)
                            internal_fail "ERROR: requested language pack not recognised $REQUESTED_LANGUAGE_PACK. Halted."
                            ;;
                    esac
                fi
            done
        fi
        umount "$temp_conf_dir"
    fi

    # The mfd may be pre 55 so we need to check /usr/share/NOS/translations/language_pack
    if [ -z "$REQUESTED_LANGUAGE_PACK" ]; then
        if ! mountpoint -q /mnt; then
            mount /mnt || true
        fi
        has_usr_partition=false
        usr_dir=/mnt/usr
        have_emmc && has_usr_partition=true
        if $has_usr_partition; then
            if ! mountpoint -q "$usr_dir"; then
                mount "$usr_dir" || true
            fi
        fi
        if [ -e "$usr_dir"/share/NOS/translations/language_pack ]; then
            LANGUAGE_PACK_FILE=$(cat "$usr_dir"/share/NOS/translations/language_pack | tr -d ' ' | tr '[:upper:]' '[:lower:]')
            case "$LANGUAGE_PACK_FILE" in
                easterneuropean|russianukrainian|middleeastern|asian)
                    REQUESTED_LANGUAGE_PACK="$LANGUAGE_PACK_FILE"
                    ;;
            esac
        fi
        if $has_usr_partition && mountpoint -q "$usr_dir"; then
            umount "$usr_dir"
        fi
        if mountpoint -q /mnt; then
            umount /mnt
        fi
    fi
    if [ -n "${PERSIST_LANG_DISABLE:-}" ]; then
        # Print the warning if the language pack is going to remove not supported languages.
        if [ "${REQUESTED_LANGUAGE_PACK}" = "${PERSIST_LANG_DISABLE}" ]; then
            splashy_update "print WARNING: This updater does not support ${REQUESTED_LANGUAGE_PACK} language pack.
It will be deleted, for reinstalling the language pack please contact the dealer."
            REQUESTED_LANGUAGE_PACK=
            sleep 5
        fi
        # Delete disabled language package
        if ! mountpoint -q /mnt; then
            mount /mnt || true
        fi
        if mountpoint -q $factorydata_directory || mount $factorydata_directory; then
            if [ -f "$factorydata_directory"/translations/"${PERSIST_LANG_DISABLE}".tar.xz ]; then
                mount -o remount,rw $factorydata_directory
                rm -rf "$factorydata_directory"/translations/"${PERSIST_LANG_DISABLE}".tar.xz
            fi
            umount $factorydata_directory
        fi
        if mountpoint -q /mnt; then
            umount /mnt
        fi
    fi
else
    HAVE_LANGUAGE_PACKS=false
fi

# Check if updater is Russian
if [ "${TARGET_LANGUAGE_PACK:-}" = "russianukrainian" ]; then
    temp_conf_dir=/tmp/persistent_languages

    if ! mountpoint -q /mnt; then
        mount /mnt || true
    fi

    # Delete unlock code if present
    mkdir -p "$temp_conf_dir"
    if mount -t ubifs -o rw ubi0:NOS "$temp_conf_dir"; then
        if [ -d "$temp_conf_dir"/features ]; then
            for FEATURE_FILE in $(ls "$temp_conf_dir"/features); do
                if [ "$FEATURE_FILE" -gt 128 -a "$FEATURE_FILE" -lt 133 ]; then
                    rm -rf "$temp_conf_dir"/features/"$FEATURE_FILE"
                fi
            done
        fi
        umount "$temp_conf_dir"
    fi

    # Delete language packages if present
    if mountpoint -q $factorydata_directory || mount $factorydata_directory; then
        if [ -d "$factorydata_directory"/translations ]; then
            mount -o remount,rw $factorydata_directory
            rm -rf "$factorydata_directory"/translations/*
        fi
        umount "$factorydata_directory"
    fi
    if mountpoint -q /mnt; then
        umount /mnt
    fi
fi

# HFP-1542: Save boot and kernel components to tmpfs (so removing SD doesn't brick device)
CACHEDIR="/tmp/upd-cache-$$/"           # Note: Trailing / is required
mkdir -p "$CACHEDIR" || CACHEDIR=""

validate_component ${ROOT_PAYLOAD} || corrupt_component_fail root
validate_component ${USR_PAYLOAD} || corrupt_component_fail usr
SHA1CHECK_SAVEDIR="$CACHEDIR"
validate_component boot.bin || corrupt_component_fail boot
validate_component kernel.bin || corrupt_component_fail kernel
SHA1CHECK_SAVEDIR=""

# If the UBI seems to be missing or corrupt, just bail out
attach_check_ubi || internal_fail "ERROR: UBI volumes corrupted. Halted"

ROOTUBI=$(find_ubi_volume_num_from_name root)
if [ -z $ROOTUBI ]; then
  corrupt_component_fail "ubi root"
fi

echo "Showing 'installing update' notification."
splashy_update "print Installing update. Please wait...
Do not turn off during update, as
this may damage your device."

update_kernel_or_fail "${CACHEDIR}kernel.bin"

if [ -n "${CONVCODENAME:-}" ]; then
  MINBOOTVER=-1
elif $ISMX6; then
  # Forced bootloader update when built from trunk
  case "$PROC_SUB_FAMILY" in
  ull)
    MINBOOTVER=-1
    ;;
  *)
    MINBOOTVER=8.11
    ;;
  esac
else
    MINBOOTVER=3
fi
update_boot_or_fail "${CACHEDIR}boot.bin" $MINBOOTVER || internal_fail "ERROR: bootloader installation failed. Halted."

[ -n "$CACHEDIR" ] && rm -fr "$CACHEDIR"

${DEBUG} && splashy_update "print Updating root partition..."

# HFP-857: Save/restore some files from RFS if sysconfig flags enabled.
BACKUP_TARBALL=""
if mount -t ubifs -o ro ubi0:NOS /mnt; then
  if [ -d /mnt/sysconfig ]; then
    mkdir -p /tmp && BACKUP_TARBALL="/tmp/saved-files.tar"
  fi
  umount /mnt

  if [ -n "$BACKUP_TARBALL" ] && mount /mnt; then
    tar -C /mnt -cf "$BACKUP_TARBALL" \
      etc/shadow \
      etc/ssh    etc/dropbear \
      root/.ssh 2>/dev/null || true
    umount /mnt
  fi
fi

ubiupdatevol -t /dev/${ROOTUBI}
mount -o rw,compr=zlib /mnt
{
  get_upd_component "$ROOT_PAYLOAD" | xzcat | tar -x -C /mnt
} || internal_fail "ERROR: root installation failed. Halted."

if [ -s "$BACKUP_TARBALL" ]; then
  echo "Restoring files from previous installation:"
  tar -C /mnt -xvf "$BACKUP_TARBALL" || true
  rm "$BACKUP_TARBALL"
  sync
fi

# Ensure factorydata file system is mounted
has_mountable_factorydata=false
if mountpoint -q $factorydata_directory || mount $factorydata_directory; then
    has_mountable_factorydata=true

    # NAND-only devices with root volume <= 225MiB require a factorydata overlay
    if ! have_emmc &&
        root_mibibytes=$(($(cat /sys/class/ubi/${ROOTUBI}/data_bytes) / 1024 / 1024)) &&
        [ $root_mibibytes -le 225 ]
    then
        case "$FAMILY_NAME" in
            FloydJr|FloydSr|Porky|Bobo|Anchovy)
                factorydata_overlay="${factorydata_directory}/overlay"
                ;;
        esac
    fi
fi

if [ -n "${factorydata_overlay:-}" ]; then
    mount -o remount,rw "$factorydata_directory"
    rm -fr "$factorydata_overlay"

    # HFP-3082: Delete pre-preproduction demo platinum data
    charts_dir="${factorydata_directory}/charts/Navionics/Navionic/Charts"
    if [ -d "$charts_dir" ]; then
        case "$FAMILY_NAME" in
        FloydJr|FloydSr|Porky|Bobo)
            find "$charts_dir" -mindepth 1 -type f ! -name "*.nv2" -exec rm -rf {} \;
            # Only delete empty directories
            find "$charts_dir" -mindepth 1 -depth -type d -exec rmdir {} \; 2>/dev/null
        ;;
        esac
    fi

    # Move resources, translations and fonts to the overlay for devices with root volume <= 225MiB
    ovl_dir_list='usr/share/NOS/resources usr/share/NOS/translations usr/share/fonts'

    # Move Qt to the overlay for Floyd Jr and Floyd Sr with root volume <= 155MiB
    # Same for Anchovy/Cruise, too small root filesystem
    case "$FAMILY_NAME" in
    FloydJr|FloydSr)
        if [ $root_mibibytes -le 155 ]
        then
            ovl_dir_list="usr/lib/qt-5.12.9-imx61-shared $ovl_dir_list"
        fi
        ;;
    Anchovy)
        ovl_dir_list="usr/lib/qt-5.12.9-imx61ul-shared $ovl_dir_list"
        ;;
    esac

    # Configure overlay directories
    for ovl_dir in \
        $ovl_dir_list
    do
        ovl_dst="/mnt/${ovl_dir%/*}"
        ovl_rel=$(printf '%s\n' "${ovl_dir%/*}" | sed 's|[^/]\+|..|g')  # eg "../.."
        mkdir -p "${factorydata_overlay}/${ovl_dir}" "$ovl_dst"
        ln -s "${ovl_rel}${factorydata_overlay#"/mnt"}/${ovl_dir}" "$ovl_dst"
    done
elif [ -n "${FACTORYDATA_OVERLAY_PAYLOAD:-}" ]; then
    factorydata_overlay="${factorydata_directory}/overlay"
    mount -o remount,rw "$factorydata_directory"
    rm -fr "$factorydata_overlay"
    mkdir -p "$factorydata_overlay"
    get_upd_component "$FACTORYDATA_OVERLAY_PAYLOAD" | xzcat | tar -x -C "$factorydata_overlay"
fi

# For Gilligan/S3009, $FAMILY_NAME=Forefraz, $THISCODENAME=gilligan
if $has_mountable_factorydata && [ -n "${S5100_UPD_PAYLOAD:-}" ] ; then
    ${DEBUG} && splashy_update "print Updating Yoshi updater..."
    validate_component "$S5100_UPD_PAYLOAD" || corrupt_component_fail "S5100 upd"
    mount -o remount,rw "$factorydata_directory"
    s5100_factorydata_dir="${factorydata_directory}/s5100-updater"
    rm -rf "${s5100_factorydata_dir}"
    mkdir -p "${s5100_factorydata_dir}"
    get_upd_component "$S5100_UPD_PAYLOAD" > "${s5100_factorydata_dir}/${S5100_UPD_PAYLOAD}"
fi

${DEBUG} && splashy_update "print Updating usr partition..."

HAS_USR=true
case "$USR_PAYLOAD" in
*.img.xz)
  # usr filesystem image (of unspecified type)
  if have_emmc; then
    get_upd_component "$USR_PAYLOAD" | xzcat | dd of=/dev/mmcblk0p1 bs=1M
    mount -o rw /dev/mmcblk0p1 /mnt/usr || HAS_USR=false
  else
    LOOP_IMG=/tmp/loop.img
    LOOP_MNT=/tmp/loop-mnt
    {
      mount -o remount,size=100% / || true
      get_upd_component "$USR_PAYLOAD" | xzcat > "$LOOP_IMG" &&
      mkdir -p "$LOOP_MNT"                                   &&
      mount -o ro,loop "$LOOP_IMG" "$LOOP_MNT"               &&
      mkdir -p /mnt/usr                                      &&
      tar -C "$LOOP_MNT" -cf - . | tar -C /mnt/usr -xf -
    } || internal_fail "ERROR: usr installation failed. Halted."
    umount "$LOOP_MNT"
    rm "$LOOP_IMG"
  fi
  ;;

*)
  # usr filesystem tarball
  if have_emmc; then
    mkfs.ext2 -m 0 -L usr -i $((32*1024)) /dev/mmcblk0p1  # HFP-577: -i (bytes-per-inode) = 32k
    # HFP-1782: -i (interval-between-checks) = 0, -c (max-mount-counts) = 0
    # Do not schedule e2fsck's based on mount counts or time interval.
    tune2fs -c 0 -i 0 /dev/mmcblk0p1
    mount -o rw /mnt/usr
  fi

  {
    get_upd_component "$USR_PAYLOAD" | xzcat | tar -x -C /mnt/usr
  } || internal_fail "ERROR: usr installation failed. Halted."
  ;;
esac

# HFP-1652 Remove burnin client to save space
# HFP-4223: Ubiqconn needs BurninClient to modify the chart SKU on Vladimir
if [ -e /mnt/usr/sbin/BurninClient -a "$FAMILY_NAME" != "Vladimir" ]; then
    rm /mnt/usr/sbin/BurninClient
fi
if [ -n "$REQUESTED_LANGUAGE_PACK" ]; then
    echo "Installing $REQUESTED_LANGUAGE_PACK language pack..."
    ${DEBUG} && splashy_update "print Installing $REQUESTED_LANGUAGE_PACK language pack..."
    # Remove the default language pack before overlaying ours on top
    if [ -d /mnt/usr/share/NOS/translations ]; then
        rm -rf /mnt/usr/share/NOS/translations
    fi
    mkdir -p /mnt/usr/share/NOS/translations
    {
        get_upd_component "${REQUESTED_LANGUAGE_PACK}".tar.xz | xzcat | tar -x -C /mnt/usr/share/NOS/translations
    } || {
        splashy_update "print ERROR: This updater does not support language pack ${REQUESTED_LANGUAGE_PACK}
Contact dealer.
Unit will reboot in 15 seconds..."
        sleep 15
        wait_for_media_reboot
        exit 0
    }
fi

if [ -n "${factorydata_overlay:-}" -o -n "${s5100_factorydata_dir:-}" ]; then
    mount -o remount,ro "$factorydata_directory"
fi

mount --bind /run /mnt/run
mount --bind /dev /mnt/dev
mount --bind /sys /mnt/sys
mount --bind /proc /mnt/proc
for TTY in /dev/ttymxc*; do
  ln -s ${TTY#/dev/} ${TTY/mxc/S}
done

# Update firmware during update, each boot will check
if [ "${HAS_USR}" = "true" -a -x /mnt/etc/rc.d/rc.stm32 ]; then
  ${DEBUG} && splashy_update "print Checking STM32 firmware..."

  if [ "$FAMILY_NAME" = "Hatchetfish" ] && [ $(( $(hf-sync version) )) -gt 0 ]; then
    # Cooperatively update the companion micro firmware.
    # This procedure closely resembles code in RFS:/etc/rc.S, except that
    # FAMILYID->THISCODENAME and rc.stm32 requires a "chroot /mnt" prefix.

    if chroot /mnt /etc/rc.d/rc.stm32 is_update_reqd; then
      MCU_UPD_REQD=1
    else
      MCU_UPD_REQD=0
    fi

    if [ $(hf-sync xch_mcu_upd_reqd $MCU_UPD_REQD) != "0" ]; then
      chroot /mnt /etc/rc.d/rc.stm32 update
      hf-sync post_mcu_upd_sync
    fi
  fi
fi

# HFP-926: Temporarily disable iGPS update due to serial port bug.
#if [ -x /mnt/etc/rc.d/rc.igps ]; then
#  ${DEBUG} && splashy_update "print Checking GPS firmware..."
#  chroot /mnt /etc/rc.d/rc.igps check || true
#fi

for TTY in /dev/ttyS*; do
  rm $TTY
done
umount /mnt/proc
umount /mnt/sys
umount /mnt/dev
umount /mnt/run || true

HAVE_SIM_MEDIA=false
if ls -d "${UPDDIR}"/[Ss][Ii][Mm][Ss] >/dev/null 2>/dev/null ; then
   HAVE_SIM_MEDIA=true
fi

if ${HAVE_SIM_MEDIA}; then
   # Clear all existing simulators.
   libupdate_sims_delete
fi

if $HAVE_SIM_PAYLOAD; then
   echo "Writing simulator files"
   ${DEBUG} && splashy_update "print Writing simulator files"

   mount -o remount,rw $factorydata_directory

   DESTPREFIX=$factorydata_directory/simulator
   cd ${DESTPREFIX}
   EXISTINGFILES=$(find -type f | sed 's/\.\///')
   cd /

   get_upd_component simulator.tar.gz | tar xz manifest
   for f in ${EXISTINGFILES}; do
     echo -n "${f}: "
     if ! grep -q $f manifest; then
       echo "Not required. Deleting."
       rm ${DESTPREFIX}/${f}
     else
       NEWSHA=$(grep $f manifest | awk '{print $1}')
       EXISTINGSHA=$(sha1sum ${DESTPREFIX}/${f} 2>/dev/null | awk '{print $1}')
       if [ "${NEWSHA}" != "${EXISTINGSHA}" ]; then
         echo "Updated. Adding to copy list."
         COPYFILES="${COPYFILES} $(echo ${f})"
       else
         echo "Unchanged. Leaving existing file."
       fi
     fi
   done

   for f in $(awk '{print $2}' manifest); do
     if [ ! -e ${DESTPREFIX}/${f} ]; then
       echo "${f}: New. Adding to copy list."
       COPYFILES="${COPYFILES} $(echo ${f})"
     fi
   done

   if [ "${COPYFILES}" != "" ]; then
      echo Copying new files...
      ( cd $DESTPREFIX; get_upd_component simulator.tar.gz | tar xvz ${COPYFILES}; )
   fi

   sync
   unset COPYFILES DESTPREFIX EXISTINGFILES NEWSHA EXISTINGSHA f
fi

if ${HAVE_SIM_MEDIA}; then
   # Copy in the card's "sims/" directory
   libupdate_sims_copyfromcard
fi

# NSW-19786: remove dirname from log files referenced by demo scripts
case "$THISCODENAME" in
cassius|lubeck|penn)
   if demoscripts="$(ls $factorydata_directory/simulator/Demo/Scripts/*.txt)" && \
      grep -q '\<SIMULATOR_SET_\(SONAR\|RADAR\)_FILE,.*/' $demoscripts; then
      mount -o remount,rw $factorydata_directory
      sed -i 's/\(\<SIMULATOR_SET_\(SONAR\|RADAR\)_FILE,\).*\//\1/' $demoscripts
   fi
   ;;
esac

# Copy language packs to factorydata so the user can unlock other languages from NOSApp
if ${HAVE_LANGUAGE_PACKS}; then
    if $has_mountable_factorydata; then
        # HFP-1844: Ensure factorydata filesystem uses all available blocks.
        if have_emmc; then
            # Filesystem mode bsddf (default) returns total blocks minus overhead blocks.
            factdata_dev=/dev/mmcblk0p2
            factdata_fs_blocks=$(stat -f -c '%b' $factorydata_directory)
            factdata_fs_blksz=$(stat -f -c '%S' $factorydata_directory)
            factdata_fs_sectors=$((factdata_fs_blocks * (factdata_fs_blksz/512) ))
            factdata_part_sectors=$(blockdev --getsz $factdata_dev)
            e2_payload=e2progs.tar.xz
            # Only resize if < 95% partition size minus overhead blocks.
            if [ $factdata_fs_sectors -lt $(( factdata_part_sectors/20*19 )) ] && sha1check $e2_payload; then
                e2_tmp_dir=/tmp/e2progs
                mkdir -p $e2_tmp_dir
                umount $factorydata_directory
                tar -xOf "$UPDFILE" $e2_payload | xzcat | tar -x -C $e2_tmp_dir
                $e2_tmp_dir/e2fsck -fy $factdata_dev || [ $? -lt 2 ]
                $e2_tmp_dir/resize2fs $factdata_dev
                rm -rf $e2_tmp_dir
            fi
        fi
        if ! mountpoint -q $factorydata_directory; then
            mount -w $factorydata_directory
        else
            mount -o remount,rw $factorydata_directory
        fi
        TRANS_DIR="$factorydata_directory"/translations
        rm -rf "$TRANS_DIR"
        mkdir -p "$TRANS_DIR"
        for LANGUAGE_PACK in $LANGUAGE_PACKS; do
            get_upd_component "${LANGUAGE_PACK}".tar.xz > "${TRANS_DIR}"/"${LANGUAGE_PACK}".tar.xz
        done
    else
        echo "Failed to mount factory data partition. Language tarballs will not be installed."
    fi
fi

if mountpoint -q $factorydata_directory; then
   umount $factorydata_directory
fi

sync


if have_emmc && [ "${HAS_USR}" = true ]; then
  umount /mnt/usr
fi

umount /mnt

sync

if [ "$FAMILY_NAME" = "Hatchetfish" ] && [ $(( $(hf-sync version) )) -gt 0 ]; then
  # UPD_RESULT is currently unused - left here for example purposes only
  # The result after hf-sync is the maximum value specified by either CPU
  UPD_RESULT=0
  UPD_RESULT=$(hf-sync finalise_update $UPD_RESULT)
fi

stop_progress_bar

splashy_update "clear"
splashy_update "progress 100"

echo "Update Finished!"

wait_for_media_reboot

# Done!
exit 0

exit 0
###SHA1MAGIC###
a6ee229cfe38947d3959a8ae7e01897defe60314  libupdate.sh
0890ac53bf8e401dc42fbdd030aa1380415a9602  splashy.tar.xz
ae3d8dae8d5fe7c784583bb0911218d29ccafc31  kernel.bin
6e8b15c47596f2feb50c95d35718eb77ecc396cd  boot.bin
010b396ad9a8e946c02f9b57b89afa3069448287  usr.img.xz
352001fe346fc46772270967cb8bca46546a262c  root.tar.xz
ba8717b7a10d00f4e1b0e5649d8b989a5ef1dc66  easterneuropean.tar.xz
8537db07eb990f894152423042effc46be9dd449  russianukrainian.tar.xz
5d78a37ad93e0bf62cc5cb42d7517105f54b012a  standard.tar.xz
5cc7d4726cfb78e668c830fc35875220bc3e0bde  asian.tar.xz
d16a52f7bad061b958f0fe2382a8eb57c84ebb79  middleeastern.tar.xz
