#!/bin/sh
# (C) Copyright 2020
# Scott Wiederhold, s.e.wiederhold@gmail.com
# https://community.openglow.org
# SPDX-License-Identifier:    MIT
#
# This program sets the bootloader to the requested image and reboots

usage () {
  cat <<END
usage: ffboot -s|e[<partition>] [-n]
  -s: SDCARD OpenGlow/ForgeFIRM
  -e[<partition>]: eMMC
     1: Factory image 1
     2: Factory image 2
     4: OpenGlow/ForgeFIRM image
     Default:
         When run from OpenGlow/ForgeFIRM: Factory image with most recent firmwmare
         When run from Factory : Factory image 1
  -n: No reboot
END
}

REBOOT=1

if [ $# -gt 2 ]; then
  usage
  exit 2
fi

if [ $# -gt 1 ]; then
  if [ $2 = "-n" ]; then
    REBOOT=0
  else
    usage
    exit 2
  fi
fi

case "$1" in
  -s)
    MMCDEV=0
    MMCPART=1
    ;;
  -e)
    MMCDEV=1
    MMCPART=1
    if [ -d "/factory" ]; then
      V1=$(cat /factory/img1/etc/version)
      V2=$(cat /factory/img2/etc/version)
      if [ $V2 -gt $V1 ]; then
        MMCPART=2
      fi
    fi
    ;;
  -e1)
    MMCDEV=1
    MMCPART=1
    ;;
  -e2)
    MMCDEV=1
    MMCPART=2
    ;;
  -e4)
    MMCDEV=1
    MMCPART=4
    ;;
  *)
    usage
    exit 2
esac

if [ -d "/factory" ]; then
  FWCONFIG="/etc/fw_env.config"
else
  FWCONFIG="/etc/fw_env_mmcblk2.config"
fi

MMCROOT="/dev/mmcblk"$(($MMCDEV + 1))"p"$MMCPART

echo "Setting to boot from $MMCROOT"
fw_setenv -c $FWCONFIG mmcdev $MMCDEV
fw_setenv -c $FWCONFIG mmcpart $MMCPART
fw_setenv -c $FWCONFIG mmcroot $MMCROOT

if [ $REBOOT -gt 0 ]; then
  echo "Rebooting..."
  reboot
fi

exit 0
