#!/bin/bash

#
# /usr/bin/pp-uboot-flash
# Utility that flashes selected U-Boot image to the boot device.
#

# Configuration file path
UBOOT_CONF="/etc/pinephone/uboot.conf"

# Allowed and fallback RAM speeds
RAM_MHZ_ALLOWED=("492" "528" "552" "592" "624")
RAM_MHZ_DEFAULT="528"

# Check that we're running as root
if [[ ${EUID} != 0 ]]; then
  echo "Flashing U-Boot image not possible, please execute this utility as root."
  exit 1
fi

# Check that the configuration file exists
if [[ ! -r ${UBOOT_CONF} ]]; then
  echo "Flashing U-Boot not possible, file ${UBOOT_CONF} not found.  No changes made to U-Boot."
  exit 1
fi

# Get RAM_MHZ from the configuration file, preventing any malicious command injection
UBOOT_CONF_DATA=`cat ${UBOOT_CONF} | egrep '^RAM_MHZ=["]?[0-9]{3}["]?[ ]{,5}'`
eval "${UBOOT_CONF_DATA}" > /dev/null 2>&1

# Check that valid RAM_MHZ value is configured
if [[ -z ${RAM_MHZ} || ! " ${RAM_MHZ_ALLOWED[*]} " =~ " ${RAM_MHZ} " ]]; then
  echo "Invalid or no RAM_MHZ value found in ${UBOOT_CONF}, defaulting to ${RAM_MHZ_DEFAULT}."
  RAM_MHZ=${RAM_MHZ_DEFAULT}
fi

# Get the device that the root resides on, and remove "/dev/" from the device name
ROOT_DEV=`findmnt / -o source -n | cut -d "[" -f 1 | cut -d "/" -f 3`

# Get the full real name of the root device, which is usually "/dev/mmcblk0"
ROOT_DEV_NAME="/dev/"`echo /sys/block/*/${ROOT_DEV} | cut -d "/" -f 4`

# Verify that the determined root device is available, just in case
if [[ ! -r ${ROOT_DEV_NAME} ]]; then
  echo "Flashing U-Boot not possible, device ${ROOT_DEV_NAME} not found.  No changes made to U-Boot."
  exit 1
fi

# Get the U-Boot image name and check that the image exists
UBOOT_IMAGE="/boot/u-boot-sunxi-with-spl-pinephone-${RAM_MHZ}.bin"
if [[ ! -r ${UBOOT_IMAGE} ]]; then
  echo "Flashing U-Boot not possible, file ${UBOOT_IMAGE} not found.  No changes made to U-Boot."
  exit 1
fi

# Flash the selected U-Boot image to the determined root device
echo "Flashing U-Boot image..."
dd if=${UBOOT_IMAGE} of=${ROOT_DEV_NAME} bs=8k seek=1 conv=notrunc,fsync > /dev/null 2>&1
if [[ $? = 0 ]]; then
  echo "U-Boot image that runs RAM at ${RAM_MHZ} MHz flashed to ${ROOT_DEV_NAME} successfully."
  echo "Please reboot your phone for the changes to take effect."
else
  echo "Flashing U-Boot image to ${ROOT_DEV_NAME} failed due to unknown reason."
  echo "Please try flashing the U-Boot again, or your phone may no longer boot properly."
  exit 1
fi

# EOF
