#!/bin/sh

#
# This script will move the apt's metadata (lists) and database (cache) from their
# canonical locations (/var/lib/apt and /var/cache/apt) into the /home partition 
# (/home/.apt/lib and /home/.apt/cache)
# 
# The script also will reconfigure apt to use directly those directories.
#
# syntaxis:
#           # ./move-apt-dirs.sh
#
# If the move and configuration is done correctly the word "OK" will be printed
# in the terminal.
#
# If something goes wrong, you're on your own. NO GUARANTIES.
#

# Check for root privileges
if [ `id -u` -ne 0 ]; then
  echo "You must be root to use this script."
  exit 1
fi

#
# Create a directory & copy the data
copy_data () {
    OLD=$1; NEW=$2
    [ $OLD != $NEW ] && mkdir -p ${NEW} && cp -a ${OLD}/* ${NEW}
}

#
# Add to apt a key-value 
add_apt_conf () {
    KEY=$1; VAL=$2
    cat >> /etc/apt/apt.conf.d/00aptdirs <<EOF
${KEY} "${VAL}";
EOF
}

# The new apt directories
NEWSTATEDIR="home/.apt/lib/"
NEWCACHEDIR="home/.apt/cache/"

# extract Dir variable
DIR=""
eval `apt-config shell DIR Dir`

# extract Dir::State
STATEDIR=""
eval `apt-config shell STATEDIR Dir::State`
STATEDIR=${DIR}${STATEDIR}
[ $STATEDIR = "/var/lib/apt/" ] || exit # sanity check

# extract Dir::Cache
CACHEDIR=""
eval `apt-config shell CACHEDIR Dir::Cache`
CACHEDIR=${DIR}${CACHEDIR}
[ $CACHEDIR = "/var/cache/apt/" ] || exit  # sanity check

copy_data $STATEDIR ${DIR}${NEWSTATEDIR} && add_apt_conf "Dir::State" $NEWSTATEDIR
copy_data $CACHEDIR ${DIR}${NEWCACHEDIR} && add_apt_conf "Dir::Cache" $NEWCACHEDIR

# Validation
NSTATEDIR=""
eval `apt-config shell NSTATEDIR Dir::State`
[ $NSTATEDIR = $NEWSTATEDIR ] && rm -rf ${STATEDIR} && echo -n "O"

NCACHEDIR=""
eval `apt-config shell NCACHEDIR Dir::Cache`
[ $NCACHEDIR = $NEWCACHEDIR ] && rm -rf ${CACHEDIR} && echo "K"
