#!/bin/bash

USELIST=""
CACHE="/tmp/completeuselist"
DEBUG=1

i=0
file="usebuilder_all.txt"

clear
if [ "e$1" == "e" ]; then
  useRoot="/"
else
  echo ">>> Using Data from ${1}usr/portage"
  useRoot="$1"
fi

echo ">>> USE-FLAG Extractor"
if [ $DEBUG == 1 ]; then
  echo ">>> Parsing Ebuild-Files: "
else
  echo -n ">>> Parsing Ebuild-Files: "
fi
   
for ebuild in `find ${useRoot}usr/portage/ -name "*.ebuild"`; do
  if [ $DEBUG == 0 ]; then
    i=$[$i+1]
    div=$[$i%50]
 
    if [ $div == 0 ]; then
      echo -n "."
    fi
  else
    echo "... $ebuild"    
  fi
  
  inlist=0
  cat $ebuild | grep "\`use" | grep -v "#" | cut -d"\`" -f2 | cut -d" " -f2 | cut -d"\`" -f1 > /tmp/usebuilder
  for param in `cat /tmp/usebuilder`; do
    for obj in $USELIST; do
      if [ "$param" == "$obj" ]; then
        inlist=1
      fi
    done

    if [ $inlist == 0 ]; then
      USELIST="$USELIST $param"
    fi      
  done

  echo ">>> ${ebuild}: " >> $file
  for i in `cat /tmp/usebuilder`; do printf "$i " >> $file ; done 
  echo " " >> $file
done

echo ">>> Package-USE list in: $file"

###############################

file="usebuilder_activeflag.txt"
echo ">>> Generating list of your currently activated options to: $file"
rm -f $file

source /etc/make.conf
USEOLDLIST=$USE
unset USE CHOST CFLAGS CXXFLAGS

i=0
for option in `(for obj in $USELIST; do echo $obj; done) | sort`; do
  i=$[$i+1]
  found=0
  for exoption in $USEOLDLIST; do
    if [ "$option" == "$exoption" ]; then
      found=1
    fi
  done

  printf "$i: ($found) $option \n" >> $file
done
