#!/bin/sh

set -e

echo >&2 "apt-get: $*"

LISTDIR=/var/lib/apt
#SECOPTS="--allow-unauthenticated"

# All these options make apt read the right sources list, and use APTDIR for
# everything so it need not run as root.
apt_get() {
  ARCH="$1"
  shift
  case "$ARCH" in
    foreign)
      apt-get.real \
	-o Dir::Etc::sourcelist=/etc/apt/foreign/sources.list \
	-o Dir::State=$LISTDIR/foreign \
	-o Dir::Cache=/var/cache/apt/foreign \
	-o Apt::Architecture=i386 \
	$SECOPTS "$@"
      ;;
    native)
      apt-get.real \
	-o Dir::Etc::sourcelist=/etc/apt/native/sources.list \
	-o Dir::State=$LISTDIR/native \
	-o Dir::Cache=/var/cache/apt/native \
	$SECOPTS "$@"
      ;;
    *)
      echo >&2 "apt_get: Unknown arg 1: '$ARCH'"
      exit 1
      ;;
  esac
}

front() {
  NUM="$1"
  set $(basename "$2" | tr "_" " ")
  FRONT="$1"
  shift
  while [ $# -gt $NUM ]; do
    FRONT="${FRONT}_$1"
    shift
  done
  echo "$FRONT"
}

middle() {
  NUM="$1"
  set $(basename "$2" | tr "_" " ")
  while [ $# -gt $NUM ]; do
    shift
  done
  echo "$1"
}

update() {
  # Update upstream files
  apt_get foreign update
  apt_get native update

  # Copy native files
  cp "$LISTDIR/native/lists/"*_* "$LISTDIR/lists/"

  # Mangle foreign files
  for F in $LISTDIR/foreign/lists/*_*; do
    DIR="$(dirname "$F")"
    case "$F" in
      *_Packages)
        FRONT="$(front 3 "$F")"
        MIDDLE="$(middle 3 "$F")"
        /usr/lib/ia32-libs-tools/mangle --index < "$F" > "$LISTDIR/lists/${FRONT}-i386_${MIDDLE}_binary-amd64_Packages";;
      *_binary-i386_Release)
        FRONT="$(front 3 "$F")"
        MIDDLE="$(middle 3 "$F")"
        sed 's/^\(Archive: .*\)$/\1-i386/' < "$F" > "$LISTDIR/lists/${FRONT}-i386_${MIDDLE}_binary-amd64_Release";;
      *Release)
        FRONT="$(front 1 "$F")"
        MIDDLE="$(middle 1 "$F")"
        F2="$LISTDIR/lists/${FRONT}-i386_${MIDDLE}_Release"
        sed < "$F" 's/^\(Suite: .*\)/\1-i386/' \
        | sed 's/^\(Codename: .*\)/\1-i386/' \
        | sed '1,/MD5Sum:/p;d' > "$F2"
        echo >>"$F2" " $(md5sum < "$DIR/${FRONT}_main_binary-i386_Packages" | cut -d" " -f1) $(wc -c < "$DIR/${FRONT}_main_binary-i386_Packages") main/binary-i386/Packages";;
      *Release.gpg)
        FRONT="$(front 1 "$F")"
        MIDDLE="$(middle 1 "$F")"
        cp "$F" "$LISTDIR/lists/${FRONT}-i386_Release.gpg";;
      *) echo "Ignoring $(basename "$F")";;
    esac
  done

  apt-get.real --no-list-cleanup --no-download update
}

case "$1" in
  update) update;;
  *) apt-get.real "$@";;
esac
