#!/bin/bash
#
# syntax: smart_lipo_merge filenative fileforeign fileout
#
# merges two binaries, taking the respective architecture part in case the input is fat
#

NATIVE=$1
FOREIGN=$2
FILEOUT=$3

ARCH1=i386
ARCH2=ppc
ARCH=`arch`
if [ $ARCH = $ARCH1 ]
then
    FOREIGNARCH=$ARCH2
else
    FOREIGNARCH=$ARCH1
fi

if [ `lipo -info $NATIVE | cut -d\  -f1` != "Non-fat" ]
then
  echo native file is fat -- extracting $ARCH
  lipo -thin $ARCH $NATIVE -output $NATIVE.$ARCH
else
  echo native file is thin -- using as is
  cp $NATIVE $NATIVE.$ARCH
fi

if [ `lipo -info $FOREIGN | cut -d\  -f1` != "Non-fat" ]
then
  echo foreign file is fat -- extracting $FOREIGNARCH
  lipo -thin $FOREIGNARCH $FOREIGN -output $FOREIGN.$FOREIGNARCH
else
  echo foreign file is thin -- using as is
  cp $FOREIGN $FOREIGN.$FOREIGNARCH
fi

echo merging... 
lipo -create $NATIVE.$ARCH $FOREIGN.$FOREIGNARCH -output $FILEOUT
echo cleanup..
rm $NATIVE.$ARCH
rm $FOREIGN.$FOREIGNARCH


