#!/bin/bash

set -e

if [ $# != 2 ] && [ $# != 3 ] ; then
	echo "Syntax: createlocalapt.sh <status-file> <sources.list> [<keyfile>]"
	exit 1
fi

echo "Building local directory hierachy..."
mkdir apt
export BASEDIR="`pwd`/apt"
mkdir apt/gpg
chmod go-rwx apt/gpg
mkdir apt/var
mkdir apt/lists
mkdir apt/lists/partial
mkdir apt/cache
mkdir apt/cache/archives
mkdir apt/cache/archives/partial
mkdir apt/dpkg
mkdir apt/dpkg/updates
touch apt/dpkg/available
cp $1 apt/dpkg/status
cp $2 apt/sources.list
cat > apt/apt.conf <<EOF
APT 
{
  Architecture "i386";
  // Options for apt-get
  Get 
  {
     Download-Only "true";
     Show-Upgraded "true";
     Upgrade "true";
     Download "true";
     List-Cleanup "true";
  };
  GPGV
  {
	  TrustedKeyring "${BASEDIR}/gpg/pubring.gpg";
  }
};
// Directory layout
Dir "${BASEDIR}/"
{
  // Location of the state dir
  State "var/" 
  {
     lists "${BASEDIR}/lists/";
     status "${BASEDIR}/dpkg/status";
  };
  
  // Location of the cache dir
  Cache "cache/" {
     archives "archives/";
     srcpkgcache "srcpkgcache.bin";
     pkgcache "pkgcache.bin";     
  };
  
  // Config files
  Etc "${BASEDIR}/" {
     sourcelist "sources.list";
  };
};

DPkg 
{
//   Options {"--force-overwrite";"--force-downgrade";}
   Options {"--admindir=${BASEDIR}/dpkg/";}
   // Flush the contents of stdin before forking dpkg.
   FlushSTDIN "true";
}

Debug 
{
//  pkgProblemResolver "false";
  NoLocking "true";
}
EOF
echo "Importing key files..."
if [ $# == 3 ] ; then
	GNUPGHOME="${BASEDIR}/gpg" gpg --import "$3"
else
	GNUPGHOME="${BASEDIR}/gpg" gpg --import /usr/share/apt/debian-archive.gpg
fi
echo "Updating index files..."
echo "apt-get -c"${BASEDIR}/apt.conf" update"
set +e
apt-get -c"${BASEDIR}/apt.conf" update
echo "If thi was successfull, you can now do"
echo "apt-get -c${BASEDIR}/apt.conf upgrade"
echo "or"
echo "apt-get -c${BASEDIR}/apt.conf install <something>"
echo "when you are finished copy the content of ${BASEDIR}/lists/ to your"
echo "/var/lib/apt/lists and ${BASEDIR}/cache to your /var/cacha/apt/" 
echo "good luck!"
exit 0

