#! /bin/bash
#
# Copyright 2010 Yorba Foundation
#
# This software is licensed under the GNU LGPL (version 2.1 or later).
# See the COPYING file in this distribution.
#
# libraw-config [--windows] [--exists=VERSION] [--cflags] [--libs]
#

usage() {
    printf "usage: libraw-config [--windows] [--exists=VERSION] [--cflags] [--libs]\n"
}

# library search paths
LIB_DIRS=/usr/lib:/usr/local/lib:/usr/lib64:/usr/local/lib64

# header search paths
HEADER_DIRS=/usr/include:/usr/local/include

searchpath() {
    tokenized=`echo $1 | tr : ' '`
    for dir in $tokenized; do
        if [ -f $dir/$2 ]; then
            return 0
        fi
    done
    
    return 1
}

cflags() {
    if pkg-config --silence-errors --cflags libraw_r; then
        :
    elif pkg-config --silence-errors --cflags libraw; then
        :
    elif [ $1 ]; then
        printf "%cDLIBRAW_NODLL " "-"
        output=true
    else
        # libraw.vapi will direct the compiler to the appropriate subdirectory
        :
    fi
}

libs() {
    if pkg-config --silence-errors --libs libraw_r; then
        :
    elif pkg-config --silence-errors --libs libraw; then
        :
    elif [ $1 ]; then
        printf "%clraw_r %clstdc++ %clwsock32 " "-" "-" "-"
        output=true
    else
        printf "%clraw_r %clstdc++ " "-" "-"
        output=true
    fi
}

# TODO: Cannot check version of library if no .pc file installed.
exists() {
    if pkg-config --silence-errors --exists 'libraw_r >= $3'; then
        :
    elif pkg-config --silence-errors --exists 'libraw >= $3'; then
        :
    elif ! searchpath $LIB_DIRS "libraw_r.a" || ! searchpath $HEADER_DIRS "libraw/libraw.h"; then
        printf "\nPackage libraw not found\n"
        exit 1
    fi
}

while [ $# != 0 ]; do
    option=`echo $1 | sed 's/=.*//'`
    if [ `echo $1 | grep '='` ]; then
        value=`echo $1 | sed 's/.*=//'`
    fi
    
    case $option in
        -h | --help)        usage
                            exit 0
                            ;;
        
        --windows)          windows="1"
                            ;;
        
        --exists)           if [ ! $value ]; then
                                usage
                                exit 1
                            fi
                            
                            version="$value"
                            do_exists="1"
                            ;;
        
        --cflags)           do_cflags="1"
                            ;;
        
        --libs)             do_libs="1"
                            ;;
        
        *)                  usage
                            exit 1
                            ;;
    esac
    
    shift
done

if [ $do_exists ]; then
    exists $windows $version
fi

if [ $do_cflags ]; then
    cflags $windows
fi

if [ $do_libs ]; then
    libs $windows
fi

if [ $output ]; then
    printf "\n"
fi


