#!/bin/sh

# Created 2006, Bundabrg
# Really quick'n'dirty script to pull down ipks from an installed package list.
# Theres not much error checking, but it should be fairly quick. Its pretty ugly ;-)

# Format:
#  oz-get <packagelist_file> <machine_name> [<dirname>]
# Suck down packages in <packagelist_file> <dirname>, else current dir.

# Variables
 # Change this to your specific machine mirrors
MACHINE_MIRROR="http://ewi546.ewi.utwente.nl/mirror/www.openzaurus.org/official/unstable/3.5.4//feed/machine/ \
                http://ewi546.ewi.utwente.nl/mirror/www.openzaurus.org/official/unstable/3.5.4//feed/upgrades/machine/"
                
MACHINES="c7x0 collie poodle tosa"                

 # These are all the rest. Common
MIRRORS="http://ewi546.ewi.utwente.nl/mirror/www.openzaurus.org/official/unstable/3.5.4//feed/base \
         http://ewi546.ewi.utwente.nl/mirror/www.openzaurus.org/official/unstable/3.5.4/feed/opie \
         http://ewi546.ewi.utwente.nl/mirror/www.openzaurus.org/official/unstable/3.5.4//feed/upgrades \
         http://ewi546.ewi.utwente.nl/mirror/www.openzaurus.org/official/unstable/3.5.4/feed/gpe \
         http://ewi546.ewi.utwente.nl/mirror/www.openzaurus.org/official/unstable/3.5.4/feed/x11"

# Don't change below

if [ "$2" = "" ]; then
  echo "$0 installed_packagefile macine_name [dirname]"
  echo "Pull down all the ipks that are listed in installed_packagefile to"
  echo "dirname or current dir if not specified"
  echo ""
  echo "installed_packagefile is generated by running 'ipkg list_installed' on"
  echo "a Z and piping that to a file."
  echo ""
  echo "Machine name can be one of: -"
  for i in $MACHINES; do
   echo " $i"
  done
  exit 1
fi

# Derived Variables
PACKAGEFILE=$1
MACHINENAME=$2
DIRNAME=$3

if [ ! -e "$PACKAGEFILE" ]; then
  echo "Cannot find $PACKAGEFILE. Fatal error"
  exit 1
fi

for i in $MACHINES xxx;do
  if [ "$MACHINENAME" = "$i" ];then
    break
  fi
  
  if [ "$i" = "xxx" ]; then
    echo "Invalid Machine name $MACHINENAME"
    echo "Machine name must be one of: -"
    for j in $MACHINES; do
      echo " $j"
    done
    exit 1
  fi
done

for i in $MACHINE_MIRROR; do
  MIRRORS="$MIRRORS $i/$MACHINENAME"
done

# Ok, for each item in package_list, we try get it from one of the mirros. This is a quick and
# dirty script so we just assume package is always name_ver_arm.ipk
P_NAMES=`cat $PACKAGEFILE | awk '{ printf "%s_%s_arm.ipk\n", $1, $3; } '`

if [ "$DIRNAME" != "" ]; then
  mkdir -p $DIRNAME
  cd $DIRNAME
fi

for P_ITEM in $P_NAMES; do
   # Skip if already there
  if [ -e "$P_ITEM" ]; then
    echo "Skipping $P_ITEM as it already exists."
    continue;
  fi

  for M_ITEM in $MIRRORS; do
    echo "Trying to get $P_ITEM from $M_ITEM"
    wget $M_ITEM/$P_ITEM
    if [ "$?" = "0" ]; then
      echo " - Success."
      break
    fi
  done
done
  
