#!/bin/bash
# autoport-fix-environment -- fixes libtool (*.la) library paths; runs with suid permissions
# Copyright (C) 2010 by Silvan Calarco <silvan.calarco@mambasoft.it>
#
# Released under the terms of the GNU GPL release 3 license
#
VERSION=0.8.3

me=(${0##*/} $VERSION "Wed Aug 11 2010")

function usage() {
   echo "\
${me[0]} ${me[1]}
"$"Copyright (C) 2010 Silvan Calarco <silvan.calarco@mambasoft.it>""
"$"Released under the terms of the GNU GPL v3 license"
   echo "
"$"Fixes libtool (*.la) library paths.""

"$"Usage"":
   $me [arch]

   arch             "$"Specify target architecture (default: $BUILD_ARCH)""
"

}

function fix_la_files() {
   for _lib in lib lib64; do
      [ "`ls /usr/${_lib}/*.la 2>/dev/null`" ] && {
         sed -i "s|libdir='/usr/$TARGET_PLATFORM/${_lib}'|libdir='/usr/${_lib}'|g" /usr/${_lib}/*.la
         sed -i "s|libdir='/$TARGET_PLATFORM/${_lib}'|libdir='/usr/${_lib}'|g" /usr/${_lib}/*.la
         sed -i "s|/usr/$TARGET_PLATFORM/${_lib}|/usr/${_lib}|g" /usr/${_lib}/*.la
         sed -i "s|[[:space:]]/usr/$TARGET_PLATFORM/${_lib}|[[:space:]]/usr/${_lib}/lib|g" /usr/${_lib}/*.la
      }
   done
}

function fix_la_files_cross() {
   for _lib in lib lib64; do
      [ "`ls /usr/$TARGET_PLATFORM/${_lib}/*.la 2>/dev/null`" ] && {
         sed -i "s|libdir='/usr/${_lib}'|libdir='/usr/$TARGET_PLATFORM/${_lib}'|g" /usr/$TARGET_PLATFORM/${_lib}/*.la
         sed -i "s|libdir='/${_lib}'|libdir='/usr/$TARGET_PLATFORM/${_lib}'|g" /usr/$TARGET_PLATFORM/${_lib}/*.la
         sed -i "s|/usr/${_lib}|/usr/$TARGET_PLATFORM/${_lib}|g" /usr/$TARGET_PLATFORM/${_lib}/*.la
         sed -i "s|[[:space:]]/lib/${_lib}|[[:space:]]/usr/$TARGET_PLATFORM/${_lib}/lib|g" /usr/$TARGET_PLATFORM/${_lib}/*.la
      }
   done
}

BUILD_ARCH=`uname -i`

case $BUILD_ARCH in
   i386|i486|i686) BUILD_ARCH=i586 ;;
   arm*) BUILD_ARCH=arm ;;
esac

for ((i=1; i<=$#; i++)); do
   case ${!i} in
      -h|--help) usage; exit 1 ;;
      -*) echo "Error: invalid option '${!i}'"
          usage
          exit 1
          ;;
      *) if [ "$TARGET_ARCH" ]; then
            echo "Error: unexpected option '${!i}'"
            usage
            exit 1
         fi
         TARGET_ARCH=${!i}
         ;;
   esac
done

[ "$TARGET_ARCH" ] || TARGET_ARCH=$BUILD_ARCH

BUILD_PLATFORM=`rpm --target $TARGET_ARCH --eval %{_build}`
BUILD_CPU=`echo $BUILD_PLATFORM | cut -d- -f1`
TARGET_PLATFORM=`rpm --target $TARGET_ARCH --eval %{_target_platform}`
TARGET_CPU=`echo $TARGET_PLATFORM | cut -d- -f1`

#echo "Build platform is $BUILD_PLATFORM"
#echo "Target platform is $TARGET_PLATFORM"

if [ "$TARGET_PLATFORM" != "$BUILD_PLATFORM" ]; then
   fix_la_files_cross
else
   fix_la_files
fi
exit 0
