#!bin/bash

function findDerivedData() {

cd
domin=`pwd|awk -F '/' '{printf $3}'`
if [[ -d "/Users/$domin/Library/Developer/Xcode/DerivedData" ]]; then
        echo "/Users/$domin/Library/Developer/Xcode/DerivedData"
else 
        exit 1
fi

}

function errorStatusHandle() {

case $1 in
        1 )
echo "Your DerivedData is empty"
                ;;
        2 )
echo "Your Main Project's hmap file is empty"
                ;;
        3 )
echo "Your Pods Project's hmap file is empty"
                ;;
        4 )
echo "Can't find the project [$ta] in your DerivedData"
                ;;
esac

}

function displayMainHmap() {

targetPath=$1
cd $targetPath
cd "Build/Intermediates.noindex/$2.build"
for file in `ls -S`; do
        if [[ -d $file ]]; then
                cd $file
                for next in `ls`; do
                        cd $next
                        t=${next%.*}
                        if [[ -f "$t.hmap" ]]; then
                                echo `pwd`"/$t.hmap"
                        else
                                exit 2
                        fi
                        break
                done
                break
        fi
done

}

function displayPodsHmap() {

targetPath=$1
cd $targetPath
cd "Build/Intermediates.noindex/Pods.build"
if [[ $? -ne 0 ]]; then
        exit 3
fi
for file in `ls -S`; do
        if [[ -d $file ]]; then
                cd $file
                for next in `ls -S`; do
                        cd $next
                        t=${next%.*}
                        if [[ -f "$t.hmap" ]]; then
                                echo `pwd`"/$t.hmap"
                                exit 0
                        else
                                cd ..
                                continue
                        fi
                done
                break
        fi
done
exit 3

}

function finish() {

status=$?
errorStatusHandle $status

}

function main() {

derivedData=`findDerivedData`
cd $derivedData
for target in `ls -t`; do
        out=`echo $target|egrep -o -i $1`
        realTarget=`echo $target|awk -F '-' '{print $1}'`
        if [[ $out ]]; then
                displayMainHmap "$derivedData/$target" $realTarget
                displayPodsHmap "$derivedData/$target" $realTarget
                exit 0
        fi
done
exit 4

} trap finish EXIT declare ta=$1 main $1