#!/bin/bash
#
# Script Name: rpi_oc
# Description: Manage Overclocking of the Raspberry Pi
# Author     : Konstantinos Mantzaris <kmanjaris@gmail.com>
# Web Site   : http://SlaXBMC.blogspot.com
#

if [ ! -f /boot/config.txt ] ; then mount -t auto /dev/mmcblk0p1 /boot ; fi
TMPFILE=$(mktemp -t rpi_oc.XXXXXX)

OC_OLD=$(grep arm_freq /boot/config.txt | grep -v '#' | cut -d '=' -f 2)
echo "\"700MHz\"" "\"(Default)\"" off > $TMPFILE
echo "\"850MHz\"" "\"Low Risk OC\"" off >> $TMPFILE
echo "\"900MHz\"" "\"Medium Risk OC\"" off >> $TMPFILE
echo "\"1000MHz\"" "\"High Risk OC\"" off >> $TMPFILE
echo "\"1200MHz\"" "\"May the Force Be With You!\"" off >> $TMPFILE
echo "\"Manual\"" "\"Manually edit config.txt file\"" off >> $TMPFILE
sed -i "/^\"$OC_OLD/s/off/ON/" $TMPFILE

CHOICE=$(dialog --title "Overclock Settings" --clear \
                --radiolist "\nPlease select an overclock setting:\n" 15 49 6 \
                --file $TMPFILE 3>&2 2>&1 1>&3)
case $? in
    0)
	CHOICE=$(echo $CHOICE | sed 's/MHz//g')
	if [ "$CHOICE" = "$OC_OLD" ] ; then umount /boot; rm $TMPFILE; exit 0 ; fi
	if [ "$CHOICE" = "Manual" ] ; then
	    dialog --no-lines --title "Overclock Settings" --editbox /boot/config.txt 30 70 2> $TMPFILE
	    case $? in
		0)
		    cat $TMPFILE > /boot/config.txt
		    ;;
		1)
		    umount /boot
		    rm $TMPFILE
		    dialog --title "Overclock Settings" --msgbox "\nProcess Aborted..."  7 50
		    exit 0
		    ;;
		255)
		    umount /boot
		    rm $TMPFILE
		    exit 1
	    esac
	else
	    # Comment out existing settings
	    sed -i 's/^arm_freq/#arm_freq/g' /boot/config.txt
	    sed -i 's/^sdram_freq/#sdram_freq/g' /boot/config.txt
	    sed -i 's/^core_freq/#core_freq/g' /boot/config.txt
	    sed -i 's/^gpu_freq/#gpu_freq/g' /boot/config.txt
	    sed -i 's/^over_voltage/#over_voltage/g' /boot/config.txt
	    sed -i 's/^current_limit/#current_limit/g' /boot/config.txt
	    # Uncomment requested settings
	    FLINE=$(grep -n arm_freq=$CHOICE /boot/config.txt | cut -d ':' -f 1)
	    TLINE=""
	    for i in $(grep -n "#----" /boot/config.txt | cut -d ':' -f 1) ; do
		if [ $i -gt $FLINE ] && [ "$TLINE" = "" ] ; then TLINE=$(($i-1)) ; fi
	    done
	    sed -i "$FLINE,$TLINE s/^#//" /boot/config.txt
	fi
	;;
    1)
	umount /boot
	rm $TMPFILE
	dialog --title "Overclock Settings" --msgbox "\nProcess Aborted..."  7 50
	exit 0
	;;
    255)
	umount /boot
	rm $TMPFILE
	exit 1
esac
umount /boot
rm $TMPFILE
dialog --title "Overclock Settings" --msgbox "\nIf the OC is unsuccessful use one of the following methods to recover:\n- Power up the RPI with pins 5 & 6 of the P1 header (GPIO) shorted\n- Edit the config.txt file in the SD card manually on another PC"  9 75
dialog --title "Overclock Settings" --msgbox "\nPlease restart the system for the changes to take effect"  8 50

exit 0

