#!/bin/sh

function anjuta_tags {

    FILES=""
    BASEDIR=`pwd`
    PROGDIR=. # `dirname $0`
    CFLAGS=""
    ANJUTA_TAGS_BIN="`which anjuta-tags`"
    OUTPUT_FILE=$1
    shift
    
    if [ -x "$ANJUTA_TAGS_BIN" ]
	then
	for cflag in $*
	  do
	  infile=`echo $cflag | sed 's/^-I//'`
	  if [ -d "$infile" -a "$infile" != "/usr/include" -a "$infile" != "/usr/local/include" ]
	      then
	      FILES="$FILES \"$infile/*.h\" \"$infile/*/*.h\" \"$infile/*/*/*.h\""
	  elif [ ! -d "$infile" -a -e "$infile" ]
	      then
	      FILES="$FILES $infile"
	  fi
	done
    else
	echo "Can not execute $ANJUTA_TAGS_BIN"
	exit 1
    fi
    CFLAGS="$CFLAGS $*"
    export CFLAGS
    
    FILES_COUNT=`echo $FILES | wc -w`
    
    echo "Creating $OUTPUT_FILE"
    echo "Number of files to scan: $FILES_COUNT"
    echo "Files to scan: $FILES"
    
    if [ $FILES_COUNT -gt 0 ] ; then
	rm -f $OUTPUT_FILE
	$ANJUTA_TAGS_BIN $OUTPUT_FILE $FILES 2>log.txt
	
    # If global tags file could not be generated
	if [ ! -e $OUTPUT_FILE ] ; then
	    echo "WARNING: Could not create tags file $OUTPUT_FILE!" >&2
	else
	    gzip -f $OUTPUT_FILE
	fi
    fi
}

## FILES="\"/usr/include/*.h\" \"/usr/local/include/*.h\""
FILES=""
BASEDIR=`pwd`
PROGDIR=. # `dirname $0`
CFLAGS=""
ANJUTA_TAGS="anjuta_tags"


echo "[...........................................................................]"
echo "[. Generating System tags. This may take several minutes (1 min to 20 mins}.]"
echo "[. You can go out, have a coffee and return back in 20 mins.]...............]"
echo "[...........................................................................]"

mkdir -p "$BASEDIR/tags"

# pkg-config libraries
PKG_CONFIG=`which pkg-config 2>/dev/null`
if ( [ ! -z $PKG_CONFIG ] && [ -x $PKG_CONFIG ] ) ; then
    
    PKG_DEFAULT_CONFIG_PATH=`echo $PKG_CONFIG | sed -e 's/\/bin\/pkg-config/\/lib\/pkgconfig'/`
    PKG_CONFIG_PATH="$PKG_CONFIG_PATH:$PKG_DEFAULT_CONFIG_PATH"
    PKG_DEFAULT_CONFIG_PATH=`echo $PKG_CONFIG | sed -e 's/\/bin\/pkg-config/\/lib64\/pkgconfig'/`
    PKG_CONFIG_PATH="$PKG_CONFIG_PATH:$PKG_DEFAULT_CONFIG_PATH"
	
    PKG_CONFIG_PATH_PROPER=`echo $PKG_CONFIG_PATH | sed -e 's/\:/ /g'`
    for pkg_path in $PKG_CONFIG_PATH_PROPER; do
	for pkg_file in $pkg_path/*.pc; do
		# echo "Scanning package: $pkg_file"
	    PKG_CFLAGS=`cat $pkg_file  2>/dev/null | grep -e "^\(\w\+\=\|\s*Cflags\:\)" | sed -e "s/^\s*Cflags\:\(.*\)/echo \"\1\"/" | sed -e 's/^\(\w\+\)\=\(.*\)/\1\=\"\2\"/' | sh`
		# echo $PKG_CFLAGS
	    package=`echo $pkg_file | sed -e 's/^.*\/\(.*\)\.pc/\1/'`
	    # if [ ! -e $BASEDIR/tags/$package.anjutatags.gz ] ; then
		echo "Creating tags file: $HOME/.anjuta/tags/$package.anjutatags.gz ..."
		anjuta_tags "$HOME/.anjuta/tags/$package.anjutatags" $PKG_CFLAGS > /dev/null
	    # fi
	done
    done
    echo "This is just a timestamp" > $HOME/.anjuta/system-tags.cache
fi
