#!/bin/bash
# This script checks .dep files on Zenwalk systems
# Copyright (C) 2007 Matthew Bruenig <matthewbruenig@gmail.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
NETPKGCONF="/etc/netpkg.conf"
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=

if [ -f $HOME/.depcheck ]; then
	PACKAGESTXT=`cat $HOME/.depcheck`
else
	PACKAGESTXT="/var/netpkg/db/PACKAGES.TXT"
fi

#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
  echo "depcheck uses /var/netpkg/db/PACKAGES.TXT by default. If you'd like to"
  echo "use another location for your package database, just create a ~/.depcheck"
  echo "file that includes the path to that location."
  exit 0
}

#Parase 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

[ -f "$NETPKGCONF" ] && LOGDIR="$(awk '/Package_logs/ {print $3}' <"$NETPKGCONF")"

#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}))

  #Find if there is a match
  unset 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
  	REPODIR=`sed "s/NAME:  \(.*\)-\(.*\)-\(.*\)-\(.*\).t[gl]z/NAME:  \1/" \
	  $PACKAGESTXT | grep -A1 "NAME:  $dep$" | grep LOCATION |\
	  sed "s/PACKAGE LOCATION:  \.\///"`
	if [[ -z "$REPODIR" ]]; then
		LOCMSG="(Not present in repository)"
	else
		LOCMSG="(in [$REPODIR])"
	fi
    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..."
  netpkg $missingdeps
fi
