#!/bin/bash
# This script checks .dep files on Salix systems
# Copyright (C) 2007 Matthew Bruenig <matthewbruenig~at~gmail~dot~com>
# Copyright (C) 2009 George Vlahavas <vlahavas~at~gmail~dot~com>
# This file is free software; the copyright holder gives unlimited
# permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
#
# This file is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.

#Initialize Variables
LOGDIR="/var/log/packages"
ABSENTMSG="NOT FOUND"
BEGINCOLOR="\033[1;31m"
ENDMSG="\033[0m"
DOTS=3
FILE=0
URL=0
COLOR=0
INSTALL=0
LONGEST=0
DEPFILE=

#Some Functions
err_msg() {
  echo "$1"
  exit 1
}

usage() {
  echo "Usage: depcheck [options] [file]"
  echo 
  echo "Basic Options:"
  echo "  -f, --file     use a local .dep file"
  echo "  -u, --url      use a url to a .dep file"
  echo "  -h, --help     display this dialog"
  echo 
  echo "Extra Options:"
  echo "  -c, --color    color missing dependencies red"
  echo "  -i, --install  attempt to install missing dependencies (must be root)"
  echo
  exit 0
}

#Parse parameters and configuration to reset variables accordingly
for param in $@; do
  if [ "${param:0:2}" = "--" ]; then
    case "${param:2}" in
      file)    FILE=1    ;;
      url)     URL=1     ;;
      color)   COLOR=1   ;;
      install) INSTALL=1 ;;
      help)    usage     ;;
      *)       err_msg "Option \`$param' not recognized, see depcheck --help." ;;
    esac
  elif [ "${param:0:1}" = "-" ]; then
    shortparam="$(sed 's/[a-zA-Z0-9]/& /g' <<<${param:1})"
    for character in ${shortparam}; do
      case $character in
        f) FILE=1    ;;
        u) URL=1     ;;
        c) COLOR=1   ;;
        i) INSTALL=1 ;;
        h) usage     ;; 
        *) err_msg "Option \`$character' not recognized, see depcheck --help." ;;
      esac
    done
  elif [ "${param##*.}" = "dep" ]; then
    DEPFILE="$param"
  else
    err_msg "Incorrect usage, see depcheck --help."
  fi
done

#Error Checks
[ "$#" -lt "2" ]                         && err_msg "Incorrect usage, see depcheck --help."
[ -z "$DEPFILE" ]                        && err_msg "No .dep file specified."
[ "$FILE" -ne "1" -a "$URL" -ne "1" ]    && err_msg "Must specify file or url"
[ "$FILE" -eq "1" -a "$URL" -eq "1" ]    && err_msg "Can't specify url and file."
[ "$FILE" -eq "1" -a ! -f "$DEPFILE" ]   && err_msg "File \`$DEPFILE' does not exist"
[ "$INSTALL" -eq "1" -a "$UID" -ne "0" ] && err_msg "Must be root to use install."

#Get the dependencies into a variable
if [ "$FILE" -eq "1" ]; then 
  DEPLIST="$(tr ',' ' ' <"$DEPFILE")"
elif [ "$URL" -eq "1" ]; then
  DEPLIST="$(wget -q "$DEPFILE" -O- | tr ',' ' ')"
  [ "$?" -gt "0" ] && err_msg "Download of \`$DEPFILE' failed."
fi
[ -z "$DEPLIST" ] && err_msg "\`$DEPFILE' has no dependencies listed"

#Find longest dep for dot output purposes
for dep in $DEPLIST; do
  [ "${#dep}" -gt "$LONGEST" ] && LONGEST="${#dep}"
done
LONGEST=$(($LONGEST+$DOTS))

#Check deps against package logs and print status
unset missingdeps
for dep in $DEPLIST; do
  dotnum=$(($LONGEST-${#dep}))
  unset match 
 
  # Take care of multiple deps 
  if [[ `echo $dep | grep '|'` ]];then
	  for i in `echo $dep | sed "s/|/ /g"`; do
  		  for package in ${LOGDIR}/*; do
    			name="${package##*/}"
    			if [ "${name%-*-*-*}" = "$i" ]; then
      				match+="$name  "
      				break
    			fi
  		  done
	  done
  fi

  #Find if there is a match
  for package in ${LOGDIR}/*; do
    name="${package##*/}"
    if [ "${name%-*-*-*}" = "$dep" ]; then
      match="$name"
      break
    fi
  done
  
  #Test match to see if it exists, if not fill with NOT FOUND, add missingdeps
  if [ -z "$match" ]; then
    match="$ABSENTMSG $LOCMSG"
    missingdeps="$missingdeps $dep"
  fi

  #Check if there was a match and whether color is enabled and print
  if [ "$match"  != "$ABSENTMSG $LOCMSG" -o "$COLOR" -ne "1" ]; then
    echo -n "$dep"
  else
    echo -ne "${BEGINCOLOR}$dep"
  fi
  
  #Echo the dots
  for (( i=0; i<"$dotnum"; i++ )); do
    echo -ne "."
  done
  
  #Echo status of dependency on system
  echo -e "${match}${ENDMSG}"
done

#Try to install if option is given
if [ "$INSTALL" -eq "1" ]; then
  [ -z "$missingdeps" ] && err_msg "No misssing dependencies to install."
  echo "Attempting missing dependency installation..."
  slapt-get -i $missingdeps
fi

