#!/bin/sh
#
# Script (enable-baffin-CUs.sh) by Goalque (goalque@gmail.com)
# Credit to okrasit and Fl0r!an:
#  http://www.insanelymac.com/forum/topic/313977-r9-nano/?p=2332854 
#  https://www.tonymacx86.com/threads/enable-all-cores-r9-fury-cards.209892/#post-1393445 

# Usage:
#          1) chmod +x enable-baffin-CUs.sh
#          2) sudo ./enable-baffin-CUs.sh fiji 64
#          3) sudo ./enable-baffin-CUs.sh ellesmere 36		

first_argument="$1"
second_argument="$2"
init_function=""
CU_count=""

pattern1="s/(\x48\xB8)(\x02)(\x00\x00\x00\x01\x00\x00\x00\x48\x89\x43\x54\xC7\x43\x7C)(\x08)(\x00\x00\x00)"

pattern2="s/(\x0F\x42\xC8)(\x89\x8B\x80\x00\x00\x00\x44\x88\xB3\x99\x00\x00\x00\x44\x88\x73\x20)"

pattern3="s/(\xE8)(\x49\x85\xFE\xFF)(\xBE\x48\x01\x00\x00\x4C\x89\xF7)"

if [[ "$first_argument" == "ellesmere" ]]
then
	init_function="\x46\xE4\x00\x00"
elif [[ "$first_argument" == "fiji" ]]
then
	init_function="\x73\x02\x01\x00"
elif [[ "$first_argument" == "baffin" ]]
then
	init_function="\x49\x85\xFE\xFF"
fi

if [[ "$second_argument" == 36 ]]
then
	CU_count="\x04\3\x12\5"
elif [[ "$second_argument" == 64 ]]
then
	CU_count="\x04\3\x20\5"
fi

if [[ "$init_function" != "" ]] && [[ "$CU_count" != "" ]]
then

	rsync -a /System/Library/Extensions/AMDRadeonX4100.kext/Contents/MacOS/AMDRadeonX4100 /tmp/AMDRadeonX4100
	cat /tmp/AMDRadeonX4100 | perl -pe "$pattern1"$"/\1"$CU_count"/g" | perl -pe "$pattern2"$"/\x90\x90\x90\2/g" | perl -pe $pattern3$"/\1"$init_function"\3/g" > /tmp/AMDRadeonX4100_modified

	rsync -a --delete /tmp/AMDRadeonX4100_modified /System/Library/Extensions/AMDRadeonX4100.kext/Contents/MacOS/AMDRadeonX4100

	chown -R root:wheel /System/Library/Extensions/AMDRadeonX4100.kext/Contents/MacOS/AMDRadeonX4100

	chmod -R 755 /System/Library/Extensions/AMDRadeonX4100.kext/Contents/MacOS/AMDRadeonX4100

	rm /Volumes/Macintosh\ HD/System/Library/PrelinkedKernels/prelinkedkernel 2>/dev/null

	rm /Volumes/Macintosh\ HD/System/Library/Caches/com.apple.kext.caches/Startup/kernelcache 2>/dev/null

	touch /System/Library/Extensions
	echo "Rebuilding caches..."
	kextcache -q -update-volume /Volumes/Macintosh\ HD
	echo "Ready."
else
	echo "Invalid parameters."
fi