#!/bin/bash

ftpbase="/srv/ftp"
srcbase="/srv/ftp/sources"
repos="core extra testing community"

. "$(dirname $0)/../db-functions"
. "$(dirname $0)/../config"

LOCKFILE="/tmp/.sourceball.lock"

cleanup () {
	rm -f "$LOCKFILE"
    exit 0
}

ctrl_c() {
    cleanup
}

if [ -f "$LOCKFILE" ]; then
	owner="$(/usr/bin/stat -c %U $LOCKFILE)"
	echo "error: source tarball generation is already in progress (started by $owner)"
	exit 1
fi

trap cleanup 0
trap ctrl_c 2

/bin/touch "$LOCKFILE"

dirname="$(/bin/readlink -f $(/usr/bin/dirname $0))"

FAILED_PKGS=""

[ -e "$srcbase/errors.txt" ] && /bin/mv "$srcbase/errors.txt" "$srcbase/errors.txt.old"
echo "Errors occured during run:" > "$srcbase/errors.txt"

for repo in $repos; do
    for arch in ${ARCHES[@]} any; do
        export CARCH="$arch"
        ftppath="$ftpbase/$repo/os/$arch"
        if [ ! -d "$ftppath" ]; then
            echo "FTP path does not exist: $ftppath" >2
            continue
        fi
        cd $ftppath
        for pkg in *$PKGEXT; do
            pkgbase=$(getpkgbase $pkg)
            srcpath="$srcbase/"
            srcpkg="${pkg//$PKGEXT/$SRCEXT}"
            srcpkg="${srcpkg//-$arch/}"

            #Don't do anything for package in this 'blacklist'
            if grep "^$pkgbase\$" "$dirname/sourceballs.skip" >/dev/null 2>&1; then
                continue
            fi

            #Use this file to 'whitelist' or force building some sourceballs,
            # skipping the license check
            force=""
            if grep "^$pkgbase\$" "$dirname/sourceballs.force" >/dev/null 2>&1; then
                force="-f"
            fi

            if [ ! -f "$srcpath$srcpkg" ]; then
                if ! $dirname/../misc-scripts/make-sourceball $force \
                    $pkgbase $repo $arch 2>>"$srcbase/errors.txt"; then
                    FAILED_PKGS="$FAILED_PKGS $pkg"
                fi
            fi
        done
    done
done

if [ -n "$FAILED_PKGS" ]; then
    [ -e "$srcbase/failed.txt" ] && /bin/mv "$srcbase/failed.txt" "$srcbase/failed.txt.old"
    echo "The following packages failed:" > "$srcbase/failed.txt"
    echo -e $FAILED_PKGS | sed "s| |\n|g" | sort -u >> "$srcbase/failed.txt"
fi

cleanup