#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

#!/bin/bash
AUR_DIR=~/vcspkgs/aur
LOG_DIR=~/vcspkgs

if [ ! -f /usr/bin/aurdupes ];then
	echo I need aurdupes for some options
	exit
fi

if [ ! -d $AUR_DIR ]; then
	echo I need a local copy of the aur for some options
	echo Create one with \'aurtools -u\'
fi

if [ ! -d $LOG_DIR ]; then
	echo I need somewhere to put logs for some options
	echo Please create $LOG_DIR or set \$LOG_DIR
fi

function deadgitpkgs {

echo > $LOG_DIR/dead-vcs-links.log

#Store number of dev packages for progress bar
DEV_PKGS=$(find $AUR_DIR | grep /PKGBUILD | egrep "\-git/" | wc -l) #|\-svn/|\-hg/|\-bzr/|\-darcs/|\-cvs/" | wc -l)
CURRENT_PKG=0

cd $AUR_DIR

#find all git packages
for i in $(find ${AUR_DIR} -maxdepth 2 | grep "/PKGBUILD$" | grep "\-git/"); do

        #Import variables from PKGBUILD
        . $i > /dev/null 2>&1

        #Subsitute variables into url
        URL="$(eval echo ${_gitroot})"

        #Filter URL to one valid address
        #URL="$(for j in $URL; do echo $j | egrep "http://|git://|https://"; done | head -n 1)"

        if [ -z "$URL" ]; then
                #if URL does not exist then it may not use git cloning
                echo $i >> $LOG_DIR/dead-vcs-links.log
                echo Does not conform to VCS PKGBUILD Guidelines so I cant get a VCS URL >> $LOG_DIR/dead-vcs-links.log
                echo >> $LOG_DIR/dead-vcs-links.log
        #if url has a .git file or is a git url then use git, otherwise use wget
        elif [ -n "$(echo $URL | grep "\.git")" ]; then
                (git ls-remote $URL > /dev/null 2>&1 || echo -e $i '\n'Broken URL: $URL'\n' >> $LOG_DIR/dead-vcs-links.log)&
        #elif [ -n "$(echo $URL | egrep "http://|git://")" ]; then
        #       URL=$(echo $URL | sed "s/http:\/\//git:\/\//g")
        #       git ls-remote $URL > /dev/null 2>&1 || echo -e $i '\n'Broken URL: $URL'\n' >> $LOG_DIR/dead-vcs-links.log
        #else
        #       wget --spider -t 3 -T 10 $URL > /dev/null 2>&1 || echo -e $i '\n'Broken URL '(wget)': $URL'\n' >> $LOG_DIR/dead-vcs-links.log
        fi

        #Clear important variable incase non existant in next loop run
        _gitroot=

        #Progress bar
        CURRENT_PKG=$[$CURRENT_PKG+1]
        echo -ne $[100*$CURRENT_PKG/$DEV_PKGS]% done '\r'
done

CURRENT_PKG=30
while [ "$(jobs | wc -l)" != "0" ] && [ "$CURRENT_PKG" != "0" ]; do
echo -ne Waiting for $(jobs | wc -l) background processes to finish. Timing out in $CURRENT_PKG '\r'
sleep 5
CURRENT_PKG=$[$CURRENT_PKG-5]
done
echo -ne Killing $(jobs | wc -l) timed out background processes '\n'
# Some trickery to hide killed message
exec 3>&2          # 3 is now a copy of 2
exec 2> /dev/null  # 2 now points to /dev/null
kill $(jobs -p)
sleep 1            # sleep to wait for processes to die
exec 2>&3          # restore stderr to saved
exec 3>&-          # close saved version

}

case "$1" in
  -A) #List packages with alias suffixes
	aurdupes -A
	;;
  -d) #Find badly named VCS packages
      for i in $(find $AUR_DIR | egrep "\-dev/|\-devel/" | grep "/PKGBUILD$"); do
	if [ -n "$(cat $i | egrep "gitroot|svntrunk|hgroot|bzrtrunk|darcstrunk|cvsroot")" ]; then
	  echo $i | rev | cut -d "/" -f 2 | rev
	fi
      done
	;;
  -D) #List packages with the same name
	aurdupes -D
	;;
  -h | --help) #Print help
	echo -e 'Usage: aurtools OPTION
	 Options:
	 -A: List packages with alias suffixes
	 -d: Find VCS packages with -dev/-devel suffixes
	 -D: List packages with the same name
	 -h: Print this help
	 -s: List packages with dead source links
	 -u: Update local AUR pull (Required for some options)
	 -v: Find VCS packages with dead repositories
	 -V: Find duplicate VCS Packages'
	;;
  -s) #Find packages with dead source links
	#in testing
	;;
  -u) #Update local AUR
      cd $AUR_DIR/..
      if [ -d aur ] ; then
        cd aur
        git pull origin
        cd ..
      else
        git clone git://pkgbuild.com/aur.git
      fi
	#Clean deleted packages
	wget  http://cryptocrack.de/files/aurpkglist.txt.gz
	gunzip -f aurpkglist.txt.gz
	cat aurpkglist.txt | grep http | cut -d " " -f 1 | sort > formattedaurpkglist.txt
	find $AUR_DIR | grep "/PKGBUILD$" | rev | cut -d "/" -f 2 | rev | sort > fullaurlist.txt
	comm -2 -3 fullaurlist.txt formattedaurpkglist.txt > aurpkglist.txt
	rm formattedaurpkglist.txt fullaurlist.txt
	for i in $(cat aurpkglist.txt); do
		rm -rf $AUR_DIR/$i
	done
	rm -f aurpkglist.txt
	;;
  -v) #Find dead VCS packages #Currently only works for git
	deadgitpkgs
	;;
  -V) #Find duplicate VCS packages
	aurdupes -V
	;;
   *) #Invalid option
	echo Nothing to do
	;;
esac

