#!/bin/sh
# -*- indent-tabs-mode: t; tab-width: 2 -*-
#
# Copyright 2009-2012 Canonical Ltd
#
# This program 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, version 3 of the License.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

# Expected arguments:
# 1 is destination directory for source
# 2 is package name
# 3 and 4 are uid and gid

set -e

SRCTMP=$(mktemp -d)
cd "$SRCTMP"

SRCDIR="$1"
PKG="$2"

apt-get update

chown _apt .
su -s /bin/sh -c "apt-get source $PKG" _apt

chown -R $3:$4 *

# Only move actual packaging files if they don't exist, but never just fail to
# expand it nor overwrite an already-expanded source dir (the user may have
# work in it).  So we backup existing directories.
mv -t "$SRCDIR" --backup=numbered $(ls -d */)

# Now just move everything else
mv -t "$SRCDIR" -u *

cd /
rm -r "$SRCTMP"

