#!/bin/sh

XRANDR=yes
XCONFIG=$1/qmake.conf
VERBOSE=$2
shift 2
IN_LIBDIRS=""
IN_INCDIRS=""
PARAMS=$@
for PARAM in $PARAMS; do
    PREFIX=`echo $PARAM | sed 's/^\(..\).*/\1/'`
    case $PREFIX in
    -L)
	CLIBDIR=`echo $PARAM | sed -e 's/^-L//'`
	IN_LIBDIRS="$IN_LIBDIRS $CLIBDIR"
	;;
    -I)
        CINCDIR=`echo $PARAM | sed -e 's/^-I//'`
        IN_INCDIRS="$IN_INCDIRS $CINCDIR"
        ;;
    *) ;;
    esac 
done

# debuggery
[ "$VERBOSE" = "yes" ] && echo "XRandR auto-detection... ($*)"

# check for the Xrandr library
XDIRS=`sed -n -e '/^QMAKE_LIBDIR_X11[	]*=/ { s/[^=]*=[	 ]*//; s/-L/ /g; p; }' $XCONFIG`
LIBDIRS="$IN_LIBDIRS $XDIRS /usr/shlib /usr/lib /lib"
F=
for LIBDIR in $LIBDIRS; do
    FOUND_LIB=`ls $LIBDIR/libXrandr.* 2>/dev/null`
    if [ ! -z "$FOUND_LIB" ]; then
	F=yes
	[ "$VERBOSE" = "yes" ] && echo "  Found XRandR lib in $LIBDIR"
	break
    fi
done
if [ -z "$F" ]; then
    XRANDR=no
    [ "$VERBOSE" = "yes" ] && echo "  Could not find XRandR lib anywhere in $LIBDIRS"
fi
    
# check for Xrandr.h and randr.h
XRANDR_H=
RANDR_H=
if [ "$XRANDR" = "yes" ]; then
    INC="X11/extensions/Xrandr.h"
    INC2="X11/extensions/randr.h"
    XDIRS=`sed -n -e '/^QMAKE_INCDIR_X11[	]*=/ { s/[^=]*=[	 ]*//; s/-I/ /g; p; }' $XCONFIG`
    INCDIRS="$IN_INCDIRS $XDIRS /usr/include /include"
    F=
    for INCDIR in $INCDIRS; do
	if [ -f $INCDIR/$INC -a -f $INCDIR/$INC2 ]; then
	    F=yes
	    XRANDR_H=$INCDIR/$INC
	    RANDR_H=$INCDIR/$INC2
	    [ "$VERBOSE" = "yes" ] && echo "  Found $INC in $INCDIR"
	    break
	fi
    done
    if [ -z "$F" ]
    then
	XRANDR=no
	[ "$VERBOSE" = "yes" ] && echo "  Could not find $INC anywhere in $INCDIRS"
    fi
fi

# verify that we are using XRandR 1.x >= 1.1
if [ "$XRANDR" = "yes" ]; then
    XRANDR_MAJOR=`grep RANDR_MAJOR $RANDR_H | awk '{ print \$3 }'`
    XRANDR_MINOR=`grep RANDR_MINOR $RANDR_H | awk '{ print \$3 }'`
    if [ -z "$XRANDR_MAJOR" -o -z "$XRANDR_MINOR" ]; then
        XRANDR=no
	[ "$VERBOSE" = "yes" ] && \
	    echo "  Could not find XRandR version."
    elif [ "$XRANDR_MAJOR" != "1" -o "$XRANDR_MINOR" -lt "1" ]; then
        XRANDR=no
	[ "$VERBOSE" = "yes" ] && \
	    echo "  Found XRandR version $XRANDR_MAJOR.$XRANDR_MINOR, version 1.1 or higher required."
    else
	[ "$VERBOSE" = "yes" ] && \
	    echo "  Found XRandR version $XRANDR_MAJOR.$XRANDR_MINOR"
    fi
fi

# done
if [ "$XRANDR" != "yes" ]; then
    [ "$VERBOSE" = "yes" ] && echo "XRandR disabled."
    exit 0
else
    [ "$VERBOSE" = "yes" ] && echo "XRandR enabled."
    exit 1
fi
