#!/bin/sh
# -*- Mode: sh; indent-tabs-mode: nil; tab-width: 2; coding: utf-8 -*-
#
# This file is part of Déjà Dup.
# © 2008,2009 Michael Terry <mike@mterry.name>
#
# Déjà Dup is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Déjà Dup is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Déjà Dup.  If not, see <http://www.gnu.org/licenses/>.

set -e

SCRIPTDIR='.'
SCRIPTDIR=$(readlink -m "$SCRIPTDIR")
SRCDIR="$SCRIPTDIR/duplicity-src"
INSTDIR="$SCRIPTDIR/duplicity"

download_tgz()
{
  mkdir -p "$SRCDIR"
  if [ ! -e "$SRCDIR/$1" ]; then
    VER=$(basename $1 .tar.gz | cut -d- -f2)
    MAJ=$(echo $VER | cut -d. -f1)
    MIN=$(echo $VER | cut -d. -f2)
    MIC=$(echo $VER | cut -d. -f3)
    if [ $MAJ -ge "0" -a $MIN -ge "6" -a $MIC -ge "01" ]; then
      wget -nv -r -l 1 -np -nd -A "$1" "https://launchpad.net/duplicity/+download" -P "$SRCDIR"
    else
      wget "http://download.savannah.gnu.org/releases-noredirect/duplicity/$1" -P "$SRCDIR"
    fi
  fi
}

install_tgz()
{
  mkdir -p "$INSTDIR"
  
  TGZ="$SRCDIR/duplicity-$1.tar.gz"
  
  if [ "$1" != "bzr" -a "$1" != "bzr-stable" ] && [ -d "$INSTDIR/duplicity-$1" ]; then
    return
  fi
  
  download_tgz $(basename "$TGZ")
  
  rm -rf "$INSTDIR/duplicity-$1"
  
  BUILDDIR=$(mktemp -d)
  tar -xzf "$TGZ" -C "$BUILDDIR"
  
  cd "$BUILDDIR"/*
  ./setup.py install --root="$INSTDIR/duplicity-$1" > /dev/null
  cd -
  
  rm -r "$BUILDDIR"
}

install_bzr()
{
  mkdir -p "$SRCDIR"
  if [ -d "$SRCDIR/duplicity-$1" ]; then
    cd "$SRCDIR/duplicity-$1"
    if LANG=C bzr update | grep "Tree is up to date"; then
      #install_tgz "bzr"
      #return
      : # ignore...  Still want to makedist.  Doesn't cost much to redo, and
        # lets us package changes made in the tree since last update
    fi
  else
    if [ "$1" = "bzr-stable" ]; then
      url="lp:duplicity/0.6-series"
    else
      url="lp:duplicity"
    fi
    bzr co "$url" "$SRCDIR/duplicity-$1"
    cd "$SRCDIR/duplicity-$1"
  fi
  if [ "$1" = "bzr-stable" ]; then
    ver="0.6.999"
  else
    ver="999"
  fi
  ./dist/makedist "$ver" # fake a really big version number
  mv "duplicity-$ver.tar.gz" "../duplicity-$1.tar.gz"
  install_tgz "$1"
}

if [ -z "$1" ]; then
  echo 'Must provide a duplicity version'
  exit 1
elif [ "$1" = "bzr" -o "$1" = "bzr-stable" ]; then
  install_bzr "$1"
  exit 0
else
  install_tgz "$1"
  exit 0
fi

