#!/bin/bash

# Copyright Jean-Philippe Guillemin <jp.guillemin@free.fr>. 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 2 of the License, or (at your option)
# any later version. Please take a look at http://www.gnu.org/copyleft/gpl.htm
#
# Netpkg is a tool for easily install or upgrade packages via the network. With Netpkg,
# you can make a minimal installation of Zenwalk Linux and install/upgrade just the
# packages you need most.
#
#


version="4.6.4"

# Globals #####################################
export LANG=en_US
export configfile="/etc/netpkg.conf"
export PATH="${PATH}:/usr/libexec"

# CLI howto ###############################################

usage() {
  echo "netpkg version $version"
  echo -en '\E[32m'"\033[1m"
  echo "usage :"
  echo "netpkg package1 package2 (patterns)..."
  echo "netpkg install package1.tgz package2.tgz ... (GZIP compression)"
  echo "netpkg install package1.txz package2.tlz ... (LZMA compression)"
  echo "netpkg upgrade|download"
  echo "netpkg remove package_name1 package_name2 ..."
  echo "netpkg I"
  echo "netpkg U"  
  echo "netpkg N"    
  echo "netpkg D"      
  echo "netpkg dotnew|mirror"
  echo "see the man page for more information"
  echo -en '\E[32m'"\033[0m"
  echo
}


# Parsing the config file ######################################

export mirrors_list=$(sed -n 's/^[ \t]*Internet_mirror[ \t]*=[ \t]*\(.*\)$/\1/p' $configfile)

local=$(sed -n 's/^[ \t]*Local_repository[ \t]*=[ \t]*\(.*\)$/\1/p' $configfile)
export local="${local:=/var/packages}"

packagelogs=$(sed -n 's/^[ \t]*Package_logs[ \t]*=[ \t]*\(.*\)$/\1/p' $configfile)
export packagelogs="${packagelogs:=/var/log/packages}"

blacklist=$(sed -n 's/^[ \t]*Black_list[ \t]*=[ \t]*\(.*\)$/\1/p' $configfile)
export blacklist="${blacklist:=aaa_base}"

keepit=$(sed -n 's/^[ \t]*Keep_packages[ \t]*=[ \t]*\(.*\)$/\1/p' $configfile)
export keepit="${keepit:=yes}"

untouchable=$(sed -n 's/^[ \t]*Protected_files[ \t]*=[ \t]*\(.*\)$/\1/p' $configfile)
export untouchable="${untouchable:=/etc/lilo.conf /boot/grub/grub.cfg /etc/fstab}"

netpkgdir=$(sed -n 's/^[ \t]*Netpkg_dir[ \t]*=[ \t]*\(.*\)$/\1/p' $configfile)
export netpkgdir="${netpkgdir:=/var/netpkg}"

dependencies=$(sed -n 's/^[ \t]*Handle_dependencies[ \t]*=[ \t]*\(.*\)$/\1/p' $configfile)
export dependencies="${dependencies:=yes}"

export http_proxy=$(sed -n 's/^[ \t]*Proxy_Socket[ \t]*=[ \t]*\(.*\)$/\1/p' $configfile)
export proxyusr=$(sed -n 's/^[ \t]*Proxy_User[ \t]*=[ \t]*\(.*\)$/\1/p' $configfile)
export proxypwd=$(sed -n 's/^[ \t]*Proxy_Password[ \t]*=[ \t]*\(.*\)$/\1/p' $configfile)
export WGET="wget"
[ "$proxyusr" ] && export WGET="wget --proxy-user=${proxyusr} --proxy-password=${proxypwd}"

logfile=$(sed -n 's/^[ \t]*Logfile[ \t]*=[ \t]*\(.*\)$/\1/p' $configfile)
if [ "$logfile" == "none" ]; then
  export logfile="/dev/null"
else
  export logfile="${logfile:=/var/log/netpkg.log}"
fi

# create the buffer directory 
mkdir -p $netpkgdir 2>/dev/null
export buffer="$netpkgdir"
mkdir -p $buffer 2>/dev/null
([ $(($(date +%s) - $(stat -c %Z $buffer/mainlist ))) -ge 600 ] && rm -f $buffer/*list )2>/dev/null

# Retrieve the last chosen mirror if any
if [ -e $buffer/last_mirror ] ; then 
  export mirror="$(tail -n1 $buffer/last_mirror)"
fi

# fetch the packages list for available packages
getpkglist(){
  cat $buffer/mainlist | sort | sed -e 's/^[^|]* *| *\([^|]*.t[glx]z\) *| .*$/\1/'
}

# fetch the packages list for package named $1
findpackagebyname(){
  cut -d " " -f2 $buffer/pkglistfile | sed -n "s/^\($1-[^\-]*-[^\-]*-[^\-]*\.t[glx]z\)$/\1/p" 
}

# Get the category for package $1
findcategorybypackage(){
  sed -n "s/^\([^ \t]*\)[ \t]*$1[ \t]*$/\1/p" $buffer/pkglistfile
}

# Build a list of installed packages
getlocalpkglist(){
  rm -f $buffer/localpkglist
  for meta in $(ls $packagelogs) ; do 
    package="$(sed -n 's/^[ \t]*PACKAGE LOCATION:[ \t]*\(.*\)[ \t]*$/\1/p' $packagelogs/$meta)"
    echo ${package##*/} >> $buffer/localpkglist
  done
}

# The main list <available> | <installed>
getmainlist(){
  rm -f $buffer/mainlist
  listbuilder -a $buffer/pkglistfile -i $buffer/localpkglist | sort > $buffer/mainlist
  selector="$(cat $buffer/last_selector)"
  selector="${selector:=a}"
  vfilter -${selector} -f $buffer/mainlist > $buffer/Ileftlist
}

# Download and process the meta file 
getmeta(){
  
  mirror="$(tail -n1 $buffer/last_mirror)"
  echo "Cleaning cache"
  rm -f $buffer/descfile
  rm -f $buffer/pkglistfile
  rm -f $buffer/PACKAGES.TXT*
  
  echo "Connecting to mirror"
  
  neterror=$($WGET -O $buffer/PACKAGES.TXT.gz $mirror/PACKAGES.TXT.gz 2>&1 | grep -E "failed:|Not Found")
  if [ "$neterror" ] ; then
    neterror=$($WGET -O $buffer/PACKAGES.TXT $mirror/PACKAGES.TXT 2>&1 | grep -E "failed:|Not Found")
    if [ "$neterror" ] ; then
      echo "Unable to connect to $mirror, please check the network or choose another mirror" 
      return 1
    fi
  else
    echo "Uncompressing meta information"
    if ! gunzip -f $buffer/PACKAGES.TXT.gz 2>/dev/null ; then 
      echo "Unable to extract meta information, please check the network or choose another mirror"
      return 1
    fi
  fi

  echo "Computing packages dependencies"
  if [ "$dependencies" = "yes" ] ; then 
    sed -n '
    /^PACKAGE NAME:.*/{
    N;N;N;N
    s/,/ /g
    s/^PACKAGE NAME:[ \t]*\(.*\)-[^-]*-[^-]*-[^-]*\.t[glx]z[ \t]*\n.*\nPACKAGE SIZE (compressed):[ \t]*\(.*\)\nPACKAGE SIZE (uncompressed):[ \t]*\(.*\)\nPACKAGE REQUIRED:[ \t]*\(.*\)/\1:\4/p
    }' \
    $buffer/PACKAGES.TXT > $buffer/depfile
  fi

    
  echo "Computing packages descriptions"
  sed -n '
  /^PACKAGE NAME:.*/{
  N;N;N;N;N;N;N;N
  s/^PACKAGE NAME:[ \t]*\(.*\)-[^-]*-[^-]*-[^-]*\.t[glx]z[ \t]*\n.*\nPACKAGE SIZE (compressed):[ \t]*\(.*\)\nPACKAGE SIZE (uncompressed):[ \t]*\(.*\)\nPACKAGE REQUIRED:[ \t]*\(.*\)\n.*\n.*\n.*\n[^ \t]*:[ \t]*\(.*\)/\1: Description :  \5\n\1: Compressed :  \2\n\1: Uncompressed :  \3\n\1: Dependencies :  \4/p
  }' $buffer/PACKAGES.TXT > $buffer/descfile 
    
    
  echo "Creating packages list"
  sed -n '
  /^PACKAGE NAME:.*/{
  N
  s/^PACKAGE NAME:[ \t]*\(.*\.t[glx]z\)[ \t]*\nPACKAGE LOCATION:[ \t]*\(\.\/\)\?\(.*\)/\3 \1/p
  }' $buffer/PACKAGES.TXT > $buffer/pkglistfile
    
    
  echo "Getting local packages list"
  getlocalpkglist    


  echo "Computing packages status"
  getmainlist
    
  # Generating a report
  echo "Synchronization with $mirror successful"

}


# take a look at local packages list to see which version of the $1 package installed
checkinstalled(){
  sed -n "s/^\($1-[^\-]*-[^\-]*-[^\-]*\.t[glx]z\)$/\1/p" $buffer/localpkglist
}


# Download ($category $package) 
download(){
  	
  mirror="$(tail -n1 $buffer/last_mirror)"
  
  [ "$(echo $package | egrep ".*\.tlz$")" ] && ZIP="lzma"
  [ "$(echo $package | egrep ".*\.txz$")" ] && ZIP="lzma"  
  [ "$(echo $package | egrep ".*\.tgz$")" ] && ZIP="gzip"
  
  if [[ -e $local/$1/$2 && ! "$($ZIP -tv $local/$1/$2 2>&1 | egrep -e "corrupt|invalid")" ]]; then
    echo "Nothing to do, $2 is already in local cache"  
    return
  else
    echo "Downloading $2"  
    
    mkdir -p $local/$1 2>/dev/null
    rm -f $local/$1/$2 2>/dev/null   
    
    # we need to get an encoded URL if any
    # url=$($WGET -O- -q $mirror/$1/ \
    #| grep ".*\.t[glx]z<\/[a|A]>" \
    #| grep "$2" \
    #| sed -e "s/^.*<\(a\|A\) \(href\|HREF\)=\"\(.*\.t[glx]z\)\">.*/\3/")
  
    url="${mirror}/${1}/${2}"
  
    # check if we've got an absolute URL :(
    if [ $( echo "$url" | egrep -e "ftp:.*|http:.*" ) ]; then
      $WGET -c -O $local/$1/$2 $url 
    else
      $WGET -c -O $local/$1/$2 $mirror/$1/$url 
    fi
  fi
  
  
}


# Checks for configuration files to update.
checkdotnew(){
  actionlist="differences yes no remove"
  echo "Checking for configuration files to update..."
  dotnewlist="$(find /etc -name "*.new")"
  if [ "$dotnewlist" ] ; then 
	  for file in $dotnewlist ; do
		origfile="$(echo $file|sed -e 's/.new//')"
		[ "$(echo $untouchable | grep $origfile)" ] && continue
		echo "Should we move $file to $origfile ?"
		select action in $actionlist ; do
		  case $action in
			differences)
			  if [ -e $origfile ] ; then
				diff -dU 1 $origfile $file | most
			  else
				echo "$file is the only one, no $origfile yet"
			  fi 
			  ;;
			yes)
			  cp -f $file $origfile
			  rm -f $file
			  break
			  ;;
		   no)
			  break
			  ;;
		   remove)
			  rm -f $file
			  break
			  ;;
		  esac
		done
	  done
  else
	echo "No \".new\" configuration files on the system"
  fi
}


# Choose a download location from mirrors available in config file
choosemirror(){

  echo "Please choose a mirror :"
  select newmirror in $mirrors_list ;do 
    [ "$newmirror" ] && mirror="$newmirror"
    break
  done
  
  # Entry format checking
  if [ ! "$(echo $mirror | egrep 'http://|ftp://')" ] ; then
    [ "$mirror" ] && echo -en '\E[31m'"\033[1mBad syntax in url to mirror $mirror\033[0m" 
  else
    echo "$mirror" >> $buffer/last_mirror
    mirrorhash="$(echo "$mirror" | md5sum | cut -d " " -f 1)"
    mkdir -p $buffer
  fi
  echo ""
  echo -en '\E[36m'"\033[1mFrom now current mirror is : $mirror\033[0m"
  echo ""
  
  # Refresh meta information database
  getmeta

}


# prompt for action (install / upgrade / reinstall / download) for a list of packages ($1) #########################
promptaction(){
echo

# this variable will track for packages installed as dependecies
processedlist=''

for pattern in $1; do

  netpkglist="$(getpkglist | grep "$pattern")"
  if [ ! "$netpkglist" ] ; then 
    echo "Package ~ $pattern : not found"
    continue
  fi
  for package in $netpkglist ; do
    
    # If we find the package in this list then it's already processed
    [ "$(echo "$processedlist" | grep "$package")" ] && continue
     
    # We need to find the category for $package
    category=$(findcategorybypackage $package)
     
    # the software name
    softname=${package%-*}; softname=${softname%-*}; softname=${softname%-*} 
     
    # take a look in pkgtool logs to see if we've got it installed
    installedpkg="$(checkinstalled $softname)"
     
    if [ -e $packagelogs/${package%%.t[glx]z} ]; then
      echo "[I][$category] Found installed $package on the repository"
      actionname="reinstall"
    elif [ "$installedpkg" ]; then
      
      if [ "$(vfilter -u -f $buffer/mainlist -q $package)" ]; then
        echo -en '\E[31m'"\033[1m[U][$category]\033[0m"
        echo -n " Found updated "
        echo -en '\E[31m'"\033[1m$package\033[0m"
        echo " on the repository : $installedpkg is installed"
        
      elif [ "$(vfilter -d -f $buffer/mainlist -q $package)" ]; then
        echo -en '\E[32m'"\033[1m[D][$category]\033[0m"
        echo -n " Found downgraded "
        echo -en '\E[32m'"\033[1m$package\033[0m"
        echo " on the repository : $installedpkg is installed"      
      fi
        
      actionname="upgrade"
        
    else
      echo -en '\E[36m'"\033[1m[N][$category]\033[0m"
      echo -n " Found "
      echo -en '\E[36m'"\033[1m$package\033[0m"
      echo " on the repository : not installed"
      actionname="install"
    fi
    actionlist="$actionname download skip"
    echo " what should I do ?"
    select action in $actionlist ; do
      case $action in
        "install" | "reinstall" | "upgrade" )
          PROMPT=1
          autoinstall $package
          PROMPT=0
          break
          ;;
        download)
          download $category $package
          break
          ;;
        skip)
          echo "Skipping package [$category]$package"
          echo
          break
      esac
    done
  done
done
}

# Check deps , then Install / Reinstall / Upgrade a list of packages
# The full and exact package name MUST be provided
autoinstall() {  

  foundblacky="0"

if [ "$1" ]; then 

  finallist='' 
  
  # We need an up to date list of installed packages
  getlocalpkglist  
  
  for package in $1 ; do
  
    # the software name
    softname=${package%-*}; softname=${softname%-*}; softname=${softname%-*} 
    
    # This package has now been processed
    processedlist="${processedlist} $package"
      
    # take a look in the blacklist 
    for blacky in $blacklist ; do
      if [ "$blacky" = "$softname" ]; then
        echo "$package is blacklisted : skipping"
        foundblacky="1"
        break
      fi 
    done
    if [ "$foundblacky" = "1" ] ; then
      foundblacky="0"
      continue
    fi   

    finallist="${finallist} $package"
    
    [ ! "$dependencies" = "yes" ] && continue

    deps="$(grep "^$softname:.*$" $buffer/depfile | cut -s -d ":" -f 2-)"
    [ ! "$deps" ] && continue

    for dep in $deps ; do
    
      # We need to find package for $dep ($dep is the short name)
      deppackage="$(sed -n "s/^.*[ \t]\($dep-[^\-]*-[^\-]*-[^\-]*.t[glx]z\)[ \t]*$/\1/p" $buffer/pkglistfile)"
      [ ! "$deppackage" ] && continue    
    
      # If it's already in the list, then skip  
      [ "$(echo $finallist | grep "$deppackage" )" ] && continue
 
      # Do we have it installed ? then skip
      [ -e $packagelogs/${deppackage%%.t[glx]z} ] && continue

      # Is it a downgrade ? then skip
      [ "$(vfilter -d -f $buffer/mainlist -q $deppackage)" ] && continue     

      # This package has now been processed
      processedlist="${processedlist} $deppackage"   

      # take a look in the blacklist 
      for blacky in $blacklist ; do
        if [ "$blacky" = "$dep" ]; then
          foundblacky="1"
          break
        fi 
      done
      if [ "$foundblacky" = "1" ] ; then
        foundblacky="0"
        continue
      fi  

      if [ "$PROMPT" = "1" ] ; then
        echo "$deppackage is required by $package : do you want to install this dependency package ?"
        select action in yes skip ; do
          case $action in
            yes)
              finallist="${finallist} $deppackage"
              break
              ;;
            skip)
              break
          esac
        done
        continue      
      fi
      finallist="${finallist} $deppackage"
    done   
  done
  
  for package in $finallist ; do

    # We need to find the category for $package
    category=$(findcategorybypackage $package)
         
    # the software name
    softname=${package%-*}; softname=${softname%-*}; softname=${softname%-*} 

    # take a look in pkgtool logs to see if we've got it installed
    installedpkg="$(checkinstalled $softname)"

    # download the package if needed
    download $category $package
    
    # Failed to download ?
    if [[ ! "$(cat $local/$category/$package)" || ! -e $local/$category/$package ]] ; then
      echo "[F] $local/$category/$package $(date)" >> $logfile
      echo "Failed to download $package, please checkout another mirror : skipping"
      continue
    fi
    
	[ "$(echo $package | egrep ".*\.tlz$")" ] && ZIP="lzma"
	[ "$(echo $package | egrep ".*\.txz$")" ] && ZIP="lzma"
	[ "$(echo $package | egrep ".*\.tgz$")" ] && ZIP="gzip"
	
    # check package integrity
    if [ "$($ZIP -tv $local/$category/$package 2>&1 | egrep -e "corrupt|invalid")" ]; then
      echo "$package is corrupted, please checkout another mirror : skipping"
      rm -f $local/$category/$package 2>/dev/null
      continue
    fi
    
    if [ -e $packagelogs/${package%%.t[glx]z} ]; then
      echo -n "Reinstalling"
      echo -e '\E[36m'"\033[1m [$category]$package\033[0m"
      upgradepkg --reinstall $local/$category/$package 
	  echo "[U] $local/$category/$package $(date)" >> $logfile
    elif [ "$(vfilter -u -f $buffer/mainlist -q $package)" ]; then
      echo -n "Upgrading"
      echo -e '\E[31m'"\033[1m [$category]$package\033[0m"
      upgradepkg $local/$category/$package
	  echo "[U] $local/$category/$package $(date)" >> $logfile
    elif [ "$(vfilter -d -f $buffer/mainlist -q $package)" ]; then
      echo -n "Downgrading"
      echo -e '\E[32m'"\033[1m [$category]$package\033[0m"
      upgradepkg $local/$category/$package  
	  echo "[U] $local/$category/$package $(date)" >> $logfile  
    else
      echo -n "Installing"
      echo -e '\E[36m'"\033[1m [$category]$package\033[0m"
      installpkg $local/$category/$package
	  echo "[I] $local/$category/$package $(date)" >> $logfile
    fi
    
    # remove package if we don't want to keep it
    if [ ! "$keepit" = "yes" ]; then
      rm -f $local/$category/$package 2>/dev/null
    fi
    
    # We need an up to date list of installed packages
    getlocalpkglist
    
  done
fi
}




# getall ###############################################
getall() {
  echo "Connecting to the packages repository..."
  echo
  for package in $(getpkglist) ; do

    if [ "$package" ]; then
    
      # We need to find the category for $package
      category=$(findcategorybypackage $package)
      
      download $category $package
      
    fi
  done


}


# upgrade the whole system ###############################################
upgradeall() {
	
  foundblacky="0"

echo "You're about to upgrade the whole system : are you sure ?"
select action in "yes" "abort" ; do
  case $action in
    yes)
      
      echo "Connecting to the packages repository..."
      echo
      for package in $(getpkglist) ; do

        if [ "$package" ]; then
          
          # We need to find the category for $package
          category=$(findcategorybypackage $package)
          # the software name
          softname=${package%-*}; softname=${softname%-*}; softname=${softname%-*} 
          # take a look in pkgtool logs to see if we've got it installed
          installedpkg="$(checkinstalled $softname)"
          
          if [ -e $packagelogs/${package%%.t[glx]z} ]; then
            echo "Found [$category]$package on the repository : already installed : skipping"
            continue
          
          elif [ -n "$installedpkg" ]; then
                    
            # take a look in the blacklist 
            for blacky in $blacklist ; do
              if [ "$blacky" = "$softname" ]; then
                echo "Found [$category]$package on the repository : blacklisted : skipping"
                foundblacky="1"
                break
              fi 
            done
            if [ "$foundblacky" = "1" ] ; then
              foundblacky="0"
              continue
            fi             
            
            if [ "$(vfilter -u -f $buffer/mainlist -q $package)" ]; then 
            # If we reached this point then this package needs to be upgraded 
              echo -n "Found "
              echo -en '\E[31m'"\033[1m[$category]$package\033[0m"
              echo " on the repository : $installedpkg is installed : upgrading"

              autoinstall $package
              
            fi
          else
            echo "Found [$category]$package on the repository : not installed : skipping"
          fi
        fi
      done
      
    break
    ;;
  abort)
    exit 0
  esac
done


}


# list packages from repository #########################
listall() {

  netpkglist="$(getpkglist)"

  [ ! "$netpkglist" ] && echo -e '\E[31m'"\033[1mFound no package on $mirror\033[0m"

  for package in $netpkglist ; do
      
    # We need to find the category for $package
    category=$(findcategorybypackage $package)
    
    # the software name
    softname=${package%-*}; softname=${softname%-*}; softname=${softname%-*} 

    # take a look in pkgtool logs to see if we've got it installed
    installedpkg="$(checkinstalled $softname)"
    
    if [ -e $packagelogs/${package%%.t[glx]z} ]; then
      if [ -n "$(echo "$1" | grep 'I')" ]; then
        echo "[I][$category] Found installed $package on the repository"
      fi
    elif [ -n "$installedpkg" ]; then
      if [ -n "$(echo "$1" | grep 'U')" ]; then    
        if [ "$(vfilter -u -f $buffer/mainlist -q $package)" ]; then
          echo -en '\E[31m'"\033[1m[U][$category]\033[0m"
          echo -n " Found updated "
          echo -en '\E[31m'"\033[1m$package\033[0m"
          echo " on the repository : $installedpkg is installed"
        fi
      fi
      if [ -n "$(echo "$1" | grep 'D')" ]; then
        if [ "$(vfilter -d -f $buffer/mainlist -q $package)" ]; then
          echo -en '\E[32m'"\033[1m[D][$category]\033[0m"
          echo -n " Found downgraded "
          echo -en '\E[32m'"\033[1m$package\033[0m"
          echo " on the repository : $installedpkg is installed"      
        fi    
      fi
    else
      if [ -n "$(echo "$1" | grep 'N')" ]; then
        echo -en '\E[36m'"\033[1m[N][$category]\033[0m"
        echo -n " Found "
        echo -en '\E[36m'"\033[1m$package\033[0m"
        echo " on the repository : not installed"
      fi
    fi
  done

}


# File protector function ######################################
protect() {
  # we backup all critical files as .old
  for protectedfile in $untouchable ; do
    [ -e $protectedfile ] && cp -f $protectedfile $protectedfile.old 2>/dev/null
  done
}

# File unprotector function 
unprotect() {
# delete backuped files in case it's the same OR no newer was added
for protectedfile in $untouchable ; do
  if [ -e $protectedfile ]; then
    newfile="$protectedfile"
    oldfile="$newfile.old"
    # clean up the redundant copy
    if [ "$(cat $oldfile 2>/dev/null | md5sum)" = "$(cat $newfile 2>/dev/null | md5sum)" ]; then
      rm $oldfile 2>/dev/null
    fi
  fi
  # Otherwise, we leave the .old copy for root to consider...
done

}

# Final cleanup ######################################
cleanup(){

  echo "Cleaning temporary files and saving meta information"

  for file in $buffer/* ; do
    [ "$(basename $file)" = "last_mirror" ] && continue
    [ "$(basename $file)" = "mainlist" ] && continue
    [ "$(basename $file)" = "depfile" ] && continue
    [ "$(basename $file)" = "descfile" ] && continue
    [ "$(basename $file)" = "pkglistfile" ] && continue
    [ "$(basename $file)" = "pkglistfile" ] && continue	
    [ "$(basename $file)" = "Ileftlist" ] && continue
    [ "$(basename $file)" = "last_selector" ] && continue
    [ "$(basename $file)" = "PACKAGES.TXT" ] && continue
	[ "$(basename $file)" = "bigdb" ] && continue
    [ "$(basename $file)" = "last_filter" ] && continue
	
    rm -rf $file 2>/dev/null
  done
  
  # We delete unchanged protected files or keep the old backuped one
  unprotect
  
  exit 0
}

# remove the buffered files on any type of exit
trap 'cleanup' TERM INT EXIT

# main( :) #########################

# We need an up to date list of installed packages
getlocalpkglist

# Local options
if [ "$1" ]; then
  case "$1" in
    -*)
      usage
      exit 1
      ;;
    'dotnew')
      checkdotnew
      exit 1
      ;;
    'mirror')
      choosemirror
      [ ! -e $buffer/pkglistfile ] && exit 1
      exit 0
      ;;
    'remove')
      export dependencies="no"
      pkgs="$*"
      removepkg ${pkgs##remove}
      exit 0
      ;;  
  esac
fi

# we protect all critical files before package processing
protect

# Network options
if [ "$1" ]; then
  if [ ! "$mirror" ] ; then 
    choosemirror
  else
    if [ ! -e "$buffer/mainlist" ] ; then 
      getmeta
    else
      getlocalpkglist
    fi
  fi 
  [ ! -e $buffer/mainlist ] && exit 1
  case "$1" in
    'upgrade')  
      upgradeall
      checkdotnew
      exit 0
      ;;
    'download')
      getall
      exit 0
      ;;
    'list')
      filter='IUND'
      [ "$2" ] && filter="$2"
      listall $filter
      exit 0
      ;;
    'I')
      listall $1
      exit 0
      ;;
    'U')
      listall $1
      exit 0
      ;;
    'N')
      listall $1
      exit 0
      ;;
    'D')
      listall $1
      exit 0
      ;;
    'install')
      export dependencies="no"
      pkgs="$*"
      autoinstall ${pkgs##install}
      exit 0
      ;;            
    *)
      promptaction "$*"
      exit 0
    esac
else
  usage
  exit 1
fi

exit 0


