#!/bin/sh

# Requires GNU Make, but some distros probably don't have the gmake symlink.
[ -z "$MAKE" ] && MAKE=make

while : ; do
	if [ -f sys/rebuild.sh ]; then
		break
	fi
	cd ..
	if [ "`pwd`" = / ]; then
		echo "Cant find sys/rebuild.sh"
		exit 1
	fi
done

Rebuild() {
	cd "$1" || exit 1
	$MAKE clean
	$MAKE -j8 || exit 1
	cd - > /dev/null
}

Build() {
	cd "$1" || exit 1
	$MAKE -j8 || exit 1
	cd - > /dev/null
}

RebuildIOSDebug() {
	Rebuild libr/debug
	# Rebuild libr/util
	# Rebuild libr/core
	Rebuild binr/radare2
	$MAKE -C binr/radare2 ios-sign
	if [ -n "${IOSIP}" ]; then
		scp binr/radare2/radare2 root@"${IOSIP}:."
	else
		echo "Set IOSIP environment variable to scp the radare2 program"
	fi
}

RebuildSpp() {
	Rebuild shlr/spp
	Rebuild libr/util
	Rebuild libr/lang
}

RebuildQJS() {
# rm -f shlr/qjs/js_repl.c
# rm -f shlr/qjs/js_r2papi.c
	make -C shlr/qjs
	Rebuild libr/lang
	touch libr/core/cmd.c
	make -C libr/core
}

RebuildJava() {
	Rebuild shlr/java
	Rebuild libr/bin
	Rebuild libr/asm
	Rebuild libr/arch
	Rebuild libr/core
}

CapstoneSubproject() {
	if grep -q '^USE_CSNEXT=1' config-user.mk 2> /dev/null; then
		echo capstone-next
	elif grep -q '^USE_CS4=1' config-user.mk 2> /dev/null; then
		echo capstone-v4
	else
		echo capstone-v5
	fi
}

RebuildCapstone() {
	make -C subprojects "$(CapstoneSubproject)" || exit 1
	make -C shlr capstone-build || exit 1
	Rebuild libr/asm
	Rebuild libr/anal
}

RebuildSdb() {
	Rebuild subprojects/sdb
	Rebuild libr/util
}

RebuildFs() {
	Rebuild libr/fs/p/grub
	Rebuild libr/fs
}

RebuildBin() {
	Rebuild libr/bin
	Rebuild libr/core
}

RebuildAr() {
	Rebuild shlr/ar
	Rebuild libr/io
}

RebuildGdb() {
	Rebuild shlr/gdb
	Rebuild libr/io
	Rebuild libr/debug
}

RebuildWinkd() {
	Rebuild shlr/winkd
	Rebuild libr/io
	Rebuild libr/debug
}

RebuildZip() {
	Rebuild shlr/zip
	Rebuild libr/io
}

RebuildTcc() {
	Rebuild shlr/tcc
	Rebuild libr/asm
}

case "$1" in
grub|fs)RebuildFs; ;;
bin)    RebuildBin ; ;;
gdb)    RebuildGdb ; ;;
ar)     RebuildAr ; ;;
winkd)  RebuildWinkd ; ;;
sdb)    RebuildSdb ; ;;
spp)    RebuildSpp ; ;;
tcc)    RebuildTcc ; ;;
bin)    RebuildBin ; ;;
zip)    RebuildZip ; ;;
java)   RebuildJava ; ;;
qjs)    RebuildQJS ; ;;
iosdbg) RebuildIOSDebug ; ;;
capstone|cs) RebuildCapstone ; ;;
*)
	echo "Usage: sys/rebuild.sh [gdb|java|capstone|sdb|iosdbg|cs|sdb|bin]"
	;;
esac
