#!/bin/bash
# shotsync-0.1.2
#   Ripped almost line for line from the sync_local() function of emerge-webrsync.
#   It's purpose is to provide an easy way to sync your Gentoo portage tree to a snapshot file.
#   Usage example: "shotsync /path/to/portage-20050507.tar.bz2" (relative path is fine, too)
#   There is no warranty of any kind associated with the use of this script.
#   Trivially created by Mike Nerone

SNAPSHOT="$1"
PORTDIR="$(/usr/lib/portage/bin/portageq portdir)"
PORTDIR="${PORTDIR%%/}"
TMPDIR="$(/usr/lib/portage/bin/portageq envvar PORTAGE_TMPDIR)"
TMPDIR="${TMPDIR%%/}/shotsync"

if [ -e "$TMPDIR" ]; then
  echo Cleaning out shotsync\'s tmpdir...
  rm -rf "$TMPDIR"
fi
mkdir -p "$TMPDIR"

echo Extracting snapshot file "$SNAPSHOT"...
if ! tar -C "$TMPDIR" -jxf "$SNAPSHOT"; then
  echo "Tar failed to extract the image. Please review the output."
  echo "Executed command: tar -C \"$TMPDIR\" -jxf \"$SNAPSHOT\""
  exit 1
fi 

# Uncomment the next line if you'd like the snapshot file you provided
#   to be deleted automatically after it is extracted.
#rm -f "$SNAPSHOT" 

# Make sure user and group file ownership is root
chown -R 0:0 portage

echo Syncing local portage tree to extracted snapshot...
rsync -av --progress --stats --delete --delete-after \
--exclude='/distfiles' --exclude='/packages' \
--exclude='/local' "$TMPDIR/portage/" "$PORTDIR"
echo "Cleaning up..."
rm -rf "$TMPDIR"
echo "Updating portage cache..."
emerge metadata

