#!/bin/bash
 
DEVICE="/dev/mmcblk0p3"
MOUNT_POINT="/tmp/noobs"
NOOBS_CONF="noobs.conf"
SUDO=''
 
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <raspbian|retropie|openelec>"
    exit 1
else
    PARTITION=$1
fi
 
if [ "$(id -u)" != "0" ]; then
    echo "Not root user, using sudo"
    SUDO='sudo'
fi
 
case $PARTITION in
    raspbian)
        PARTITION=9
        ;;
    retropie)
        PARTITION=5
        ;;
    openelec)
        PARTITION=7
        ;;
    *)
        echo "Invalid partition, exiting..."
        exit 1
esac
 
if [ ! -d "$MOUNT_POINT" ]; then
    echo "Creating mount point $MOUNT_POINT"
    $SUDO mkdir "$MOUNT_POINT"
fi
 
if mount | grep "$MOUNT_POINT" > /dev/null; then
    echo "${MOUNT_POINT} is already mounted"
else
    echo "${MOUNT_POINT} is not mounted, mounting..."
    $SUDO mount $DEVICE "${MOUNT_POINT}"
fi
 
if [ ! -f "${MOUNT_POINT}/${NOOBS_CONF}" ]; then
    echo "${MOUNT_POINT}/${NOOBS_CONF} does not exist, exiting..."
else
    echo "${MOUNT_POINT}/${NOOBS_CONF} exists, good..."
    $SUDO sed -i.bak "s,^\(default_partition_to_boot\s*=\s*\).*$,\1${PARTITION}," ${MOUNT_POINT}/${NOOBS_CONF}
fi
 
if mount | grep "$MOUNT_POINT" > /dev/null; then
    $SUDO umount "${MOUNT_POINT}"
    $SUDO rmdir "${MOUNT_POINT}"
fi
 
$SUDO reboot
