#!/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="6.1"
zenwalk_version="$(cat /etc/zenwalk-version)"

# Globals #####################################
export LANG=en_US
export configfile="/etc/netpkg.conf"
export PATH="/usr/libexec:/sbin:/bin:/usr/sbin:/usr/bin"

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

usage() {
  echo "Netpkg version $version"
  echo "You are running Zenwalk $zenwalk_version"
  echo -en '\E[32m'"\033[1m"
  echo "Simple usage :"
  echo " netpkg package1 package2 (patterns)..."
  echo
  echo "Other usages :"
  echo " netpkg install package1.txz package2.txz ... "
  echo " netpkg upgrade|download (global system upgrade using current mirror)"
  echo " netpkg remove package_name1 package_name2 ..."
  echo " netpkg list (list packages from repository"
  echo " netpkg I (list and filter only installed packages)" 
  echo " netpkg U (list and filter only updated packages)"  
  echo " netpkg D (list and filter only downgraded packages)"      
  echo
  echo "Setup commands :"       
  echo " netpkg addmirror|rmmirror URL (add or remove repository URLs from netpkg.conf)"  
  echo " netpkg dotnew (search for .new config files in the suystem and prompt for action)"
  echo -en '\E[32m'"\033[0m"
  echo
}

# Parsing config files ######################################

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

# create the netpkgdir directory 
mkdir -p $netpkgdir 2>/dev/null

# Check list of mirrors from xnetpkg and netpkg.conf
if [ -e $netpkgdir/mirrors ] ; then 
	for i in $( cat -v /var/netpkg/mirrors | sed -e 's|^..\(.\).*\(http://[^\r]*\)$|\2 |g' | grep "http" ) ; do 
		mirrors_list="$mirrors_list $(echo -n $i)"
	done
else
	mirrors_list=$(sed -n 's/^[ \t]*Internet_mirror[ \t]*=[ \t]*\(.*\)$/\1/p' $configfile)
fi
export mirrors_list

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}"

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


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

# fetch the packages list for package named $1
findpackagebyname(){
  cut -d " " -f2 $netpkgdir/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" $netpkgdir/pkglistfile
}

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

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

# Download and process the meta file 
getmeta(){
  
  mirror="$(tail -n1 $netpkgdir/last_mirror)"
  echo "Cleaning cache"
  rm -f $netpkgdir/descfile
  rm -f $netpkgdir/pkglistfile
  rm -f $netpkgdir/PACKAGES.TXT*
  
  echo "Connecting to mirror"
  
  neterror=$($WGET -O $netpkgdir/PACKAGES.TXT.gz $mirror/PACKAGES.TXT.gz 2>&1 | grep -E "failed:|Not Found")
  if [ "$neterror" ] ; then
    neterror=$($WGET -O $netpkgdir/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 $netpkgdir/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
  # cleaning PACKAGE MIRROR: lines
  sed -i '/^PACKAGE MIRROR:.*/d' $netpkgdir/PACKAGES.TXT
  
  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
    }' \
    $netpkgdir/PACKAGES.TXT > $netpkgdir/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
  }' $netpkgdir/PACKAGES.TXT > $netpkgdir/descfile 
    
    
  echo "Creating packages list"
  sed -n '
  /^PACKAGE NAME:.*/{
  N
  s/^PACKAGE NAME:[ \t]*\(.*\.t[glx]z\)[ \t]*\nPACKAGE LOCATION:[ \t]*\(\.\/\)\?\(.*\)/\3 \1/p
  }' $netpkgdir/PACKAGES.TXT > $netpkgdir/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" $netpkgdir/localpkglist
}


# Download ($category $package) 
download(){
  	
  mirror="$(tail -n1 $netpkgdir/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(){
  if [ "$mirrors_list" ] ; then
	  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
		mkdir -p $netpkgdir
		echo "$mirror" > $netpkgdir/last_mirror
		mirrorhash="$(echo "$mirror" | md5sum | cut -d " " -f 1)"
	  fi
  fi
  mirror="$(tail -n1 $netpkgdir/last_mirror 2>/dev/null)" 	  
  echo ""
  echo -en '\E[36m'"\033[1mCurrent 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"
      actionname="reinstall"
    elif [ "$installedpkg" ]; then
      
      if [ "$(vfilter -u -f $netpkgdir/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 " : $installedpkg is installed"
        
      elif [ "$(vfilter -d -f $netpkgdir/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 " : $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 " : 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:.*$" $netpkgdir/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" $netpkgdir/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 $netpkgdir/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 $netpkgdir/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 $netpkgdir/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 : 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 : blacklisted : skipping"
                foundblacky="1"
                break
              fi 
            done
            if [ "$foundblacky" = "1" ] ; then
              foundblacky="0"
              continue
            fi             
            
            if [ "$(vfilter -u -f $netpkgdir/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 " : $installedpkg is installed : upgrading"

              autoinstall $package
              
            fi
          else
            echo "Found [$category]$package : 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"
      fi
    elif [ -n "$installedpkg" ]; then
      if [ -n "$(echo "$1" | grep 'U')" ]; then    
        if [ "$(vfilter -u -f $netpkgdir/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 " : $installedpkg is installed"
        fi
      fi
      if [ -n "$(echo "$1" | grep 'D')" ]; then
        if [ "$(vfilter -d -f $netpkgdir/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 " : $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 " : 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(){
	
  # We delete unchanged protected files or keep the old backuped one
  unprotect
  
  exit 0
}

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

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

# We always 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
      ;;
    'addmirror')
      if [ "$2" ] ; then
		  echo "Internet_mirror = $2" >> $configfile
		  echo "$2" > $netpkgdir/last_mirror
		  [ ! -e $netpkgdir/pkglistfile ] && exit 1
      else
		  echo "you forgot the URL..."
      fi  
      exit 0
      ;;
    'rmmirror')
      if [ "$2" ] ; then
		  cp $configfile "${configfile}.old"
		  grep -v "Internet_mirror = $2" $configfile > "${configfile}.tmp"
		  mv "${configfile}.tmp" $configfile  2>/dev/null
      else
		  echo "you forgot the URL..."
      fi
      exit 0
      ;;
    'remove')
      export dependencies="no"
      pkgs="$*"
      removepkg ${pkgs##remove}
      exit 0
      ;;  
  esac
fi

# How old is the DB ?
mainlistage="0"
[ -e $netpkgdir/mainlist ] && mainlistage=$(stat -c %Z $netpkgdir/mainlist )

# Retrieve the last chosen mirror if any
if [ -e $netpkgdir/last_mirror ] ; then 
	export mirror="$(tail -n1 $netpkgdir/last_mirror 2>/dev/null)"
	
	if [ $(($(date +%s) - $mainlistage)) -ge 20 ] ; then
	
		echo -n "Current mirror is "
		echo -en '\E[32m'"\033[1m"
		echo $mirror
		echo -en '\E[32m'"\033[0m"	
		echo "Keep it (\"1\" for change, default keep) ?"
		echo -n "> "

		while read answer ; do
			case $answer in
			1|change)
				choosemirror
				echo -n "New mirror is "
				echo -en '\E[32m'"\033[1m"
				echo $mirror
				echo -en '\E[32m'"\033[0m"	
				break
				;;
			*)
				if [ $(($(date +%s) - $mainlistage)) -ge 120 ] ; then
					getmeta
				fi
				break
			esac
		done
	fi
else
	choosemirror
	export mirror="$(tail -n1 $netpkgdir/last_mirror 2>/dev/null)"
fi

# we protect all critical files before package processing
protect
echo
  [ ! -e $netpkgdir/mainlist ] && exit 1
# Network options
if [ "$1" ]; then
  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


