#!/bin/sh

# Copyright 1999 Raphaël Hertzog <hertzog@debian.org>
# See the README file for the license

# This script will create the Sources.gz files
# First arg = directory of the CD

set -e

PREFIX=$1
if [ -n "$NONFREE" -o -n "$EXTRANONFREE" ]; then
  SECTIONS="main contrib non-free"
else
  SECTIONS="main contrib"
fi

cd $PREFIX

# We have to scan all possible dists where sources can be
DISTS=""
DISTSNONUS=""
for i in `cd dists; echo *; cd ..`; do
    if [ ! -L "dists/$i" -a -d "dists/$i" ]; then
        if [ -d "dists/$i/main/source" -o \
	     -d "dists/$i/non-free/source" -o \
	     -d "dists/$i/contrib/source" ]; then
            DISTS="$DISTS $i"
        fi
        if [ -d "dists/$i/non-US/main/source" -o \
	     -d "dists/$i/non-US/non-free/source" -o \
	     -d "dists/$i/non-US/contrib/source" ]; then
            DISTSNONUS="$DISTSNONUS $i"
        fi
    fi
done

if [ -e "$MIRROR/dists/$CODENAME/Release" ]; then
    # Strip the MD5Sum and SHA1 field
    perl -ne 'if (/^(MD5Sum|SHA1):/) { $f=1; next; }
    if ($f) { 
	unless (/^ /) { print; $f=0 } 
    } else { print }' \
    $MIRROR/dists/$CODENAME/Release > dists/$CODENAME/Release
fi
if [ -n "$NONUS" -a -e "$NONUS/dists/$CODENAME/non-US/Release" ]; then
    # Strip the MD5Sum and SHA1 field
    perl -ne 'if (/^(MD5Sum|SHA1):/) { $f=1; next; }
    if ($f) { 
	unless (/^ /) { print; $f=0 } 
    } else { print }' \
    $NONUS/dists/$CODENAME/non-US/Release \
    > dists/$CODENAME/non-US/Release
fi

for SECT in $SECTIONS; do

	if [ -d "pool/$SECT" ]; then
		dpkg-scansources pool/$SECT > dists/$CODENAME/$SECT/source/Sources
	fi
	for DIST in $DISTS; do
		if [ -d "dists/$DIST/$SECT/source" ] ; then
			dpkg-scansources dists/$DIST/$SECT/source \
			>> dists/$CODENAME/$SECT/source/Sources
		fi
	done
	if [ -f dists/$CODENAME/$SECT/source/Sources ] ; then
		gzip --best dists/$CODENAME/$SECT/source/Sources
	fi

	if [ -n "$NONUS" -a "$CODENAME" != "slink" ]; then
		if [ -d "pool/non-US/$SECT" ]; then
			dpkg-scansources pool/non-US/$SECT \
			> dists/$CODENAME/non-US/$SECT/source/Sources
		fi
		for DIST in $DISTSNONUS; do
			if [ -d "dists/$DIST/non-US/$SECT/source" ] ; then
				dpkg-scansources dists/$DIST/non-US/$SECT/source \
					>> dists/$CODENAME/non-US/$SECT/source/Sources		
			fi
		done
		if [ -f dists/$CODENAME/non-US/$SECT/source/Sources ] ; then
			gzip --best dists/$CODENAME/non-US/$SECT/source/Sources
		fi
	fi
	
done

# Slink special case
if [ -n "$NONUS" -a "$CODENAME" = "slink" ]; then
	dpkg-scansources dists/$CODENAME/non-US/source \
	| gzip --best > dists/$CODENAME/non-US/source/Sources.gz
fi

if [ -n "$LOCAL" ]; then
	dpkg-scansources dists/$CODENAME/local/source \
	| gzip --best > dists/$CODENAME/local/source/Sources.gz
fi

exit 0
