#!/bin/sh

LIBS="librz/cons/librz_cons.a librz/util/librz_util.a  librz/bin/librz_bin.a  librz/analysis/librz_analysis.a librz/bp/librz_bp.a librz/hash/librz_hash.a librz/debug/librz_debug.a shlr/sdb/src/libsdb.a librz/core/librz_core.a librz/main/librz_main.a librz/syscall/librz_syscall.a shlr/java/librz_java.a shlr/zip/librz.a librz/socket/librz_socket.a librz/analysis/librz_analysis.a librz/flag/librz_flag.a librz/search/librz_search.a librz/reg/librz_reg.a librz/config/librz_config.a librz/io/librz_io.a librz/parse/librz_parse.a librz/bp/librz_bp.a librz/asm/librz_asm.a librz/bp/librz_bp.a librz/egg/librz_egg.a librz/analysis/librz_analysis.a librz/magic/librz_magic.a librz/lang/librz_lang.a shlr/capstone/libcapstone.a  shlr/gdb/lib/libgdbr.a shlr/tree-sitter/libtree-sitter.a shlr/rizin-shell-parser/libshell-parser.a"
cd ..

LIB=librz.a
TMP=.ar.tmp

IOSVER=1
if [ -n "${IOSVER}" ]; then
	RANLIB="xcrun --sdk iphoneos ranlib"
	AR="xcrun --sdk iphoneos ar"
else
	RANLIB=ranlib
	AR=ar
fi

rm -rf ${TMP}
mkdir -p ${TMP}
for a in ${LIBS} ; do
	${RANLIB} $a
	file "$a" | grep -q universal
	if [ $? = 0 ]; then
		ARCHS=`lipo -info $a | cut -d : -f 3-`
	else
		ARCHS=""
	fi
	if [ -n "${ARCHS}" ]; then
		for b in ${ARCHS} ; do
			mkdir -p "$TMP/$a/$b"
			ORIG="$PWD/$a.$b"
			lipo -thin $b -output $a.$b $a
			echo "cd $TMP/$a/$b : ${AR} -x $ORIG"
			( cd $TMP/$a/$b ; ${AR} -x $ORIG )
			rm -f $a.$b
		done
	else
		mkdir -p "${TMP}/${a}"
		ORIG="$PWD/$a"
		( cd $TMP/$a ; ${AR} -x $ORIG )
		echo $a
	fi
done

cd ${TMP}
OBJS=`find * -iname *.o`
if [ -z "${OBJS}" ]; then
	echo
	echo "Cannot find any object"
	echo
	exit 1
else
	rm -f "${LIB}"
	${AR} -qv "${LIB}" ${OBJS}
	${RANLIB} "${LIB}"
fi
