#!/sbin/sh
#
# Mount the system partition
#

mount_system() {
  export SYSDEV="$(readlink -nf "/dev/block/bootdevice/by-name/system")"
  export SYSFS="ext4"

  if grep -q -e"^$SYSDEV" /proc/mounts; then
    umount $(grep -e"^$SYSDEV" /proc/mounts | cut -d" " -f2)
  fi

  if [ -d /mnt/system ]; then
    SYSMOUNT="/mnt/system"
    echo 'SYSMOUNT="/mnt/system"' > /tmp/variablestorage
  elif [ -d /system_root ]; then
    SYSMOUNT="/system_root"
    echo 'SYSMOUNT="/system_root"' > /tmp/variablestorage
  else
    SYSMOUNT="/system"
    echo 'SYSMOUNT="/system"' > /tmp/variablestorage
  fi
  echo "S=$SYSMOUNT/system" >> /tmp/variablestorage

  mount -t $SYSFS $SYSDEV $SYSMOUNT -o rw,discard
}


patch_system() {
  source /tmp/variablestorage

  for i in $(ls "/tmp/system/vendor/firmware"); do
    if [ -f "$S/vendor/firmware/$i" ]; then
      rm $S/vendor/firmware/$i
    fi
    cp /tmp/system/vendor/firmware/$i $S/vendor/firmware/$i
  done
}

unmount_system() {
  source /tmp/variablestorage
  umount "$SYSMOUNT" >> /tmp/log
}


case "$1" in
  mount)
    mount_system
  ;;
  patch)
    patch_system
  ;;
  unmount)
    unmount_system
  ;;
  *)
esac

exit 0
