#!/bin/bash

DisplayUsage(){
   echo "Repository Verifier"
   echo "Usage: repoverify <space separated list of repositories>"
   echo " e.g. repoverify core updates"
   echo ""
   echo "Available repositories are:"
   echo
   smart channel --show | grep '\[' | sed -e 's/\[\(.*\)\]/"\1"/' | sort -f | sed ':b;N;s/\n/  /;bb'
   echo
}

ArgError(){
   echo
   DisplayUsage
   echo
   echo "Error in repository arguments."
   echo
   echo
}

#some basic arg verification
   args="$@"
   if [ "$args" = "" ]; then
      DisplayUsage
      exit
   else
   # (this doesn't work if all the args are not in double quotes)
      if argchek=$(smart channel --show "$@" 2>&1 >/dev/null | grep "not found" > argerror.txt);then
         ArgError
         cat argerror.txt
         exit
      fi

   fi

# smart seems to agree with the args so we can proceed


# save current channel config
   echo "Setting up. Please wait...."
   smart channel --show | sed '/\[rpm\-db\]/,/\n/ d' > channel.backup

# disable all repos (reset smart to zero)
   smart channel --show | grep '\[' | sed -e 's/\[/"/' -e 's/\]/"/' | xargs smart channel -y --disable

# hard clear the cache (just to be sure the returned data is good)
   rm -f /var/lib/smart/cache
   #un-comment the following line to force a fresh metadata download
   #rm -f /var/lib/smart/channels/*

#enable requested repos and populate the cache
   echo "Processing...."
   smart channel -y --enable "$@"
   smart update >/dev/null

#smart check --all to test the repos and print out the potential issues
   echo
   channellist=$(echo "$@" | sed 's/ /,/g')
   smart check --channels=$channellist 2>&1 | grep "Unsatisfied dependency:" | awk '{print $3}'
   #smart check --all 2>&1 | grep "Unsatisfied dependency:" | awk '{print $3}'

# restore original config
   # hacky but brief. A -y --update option to smart channel would
   # fix this, otherwise it would be better to loop through the repos and
   # set the enable/disabled config
   smart channel --show | grep '\[' | sed -e 's/\[/"/' -e 's/\]/"/' | xargs smart channel -y --remove
   smart channel -y --add channel.backup
#   rm -f /var/lib/smart/cache
   rm -f channel.backup
   rm -f argerror.txt

