#!/bin/sh

set -e

if [ "$#" -lt 3 ]; then
    echo "Usage: $0 <name> <path> <config>"
    exit 1
fi

NAME="$1"
BASE="$2"
CONFIG="$3"
THIS="$(readlink -f "$(dirname "$0")/..")"

if ! [ -f "$THIS/README.md" ]; then
    echo "$THIS/README.md does not exist"
    echo "You should call this script without relying on PATH"
    exit 1
fi

if ! [ -d "$CONFIG" ]; then
    echo "$CONFIG does not exist or is not a directory"
    exit 1
fi

CONFIG="$(readlink -f "$CONFIG")"

. "$CONFIG/config.sh"
mkdir -p "$BASE"
cd "$BASE"
mkdir -p ben build pool override
ln -sfT "$THIS" usr
ln -sfT "usr/lib/Makefile.index" Makefile

: ${ARCH:="$(dpkg-architecture -q DEB_BUILD_ARCH)"}

save_env () {
    local v
    v="$(eval "echo \$$1")"
    if [ -n "$v" ]; then
        echo "$1=\"$v\"" >> ben/env.sh
    else
        echo "$1 is empty"
        exit 1
    fi
}

rm -f ben/env.sh
save_env MIRROR
save_env ORIGIN
save_env LABEL
save_env SUITE
save_env ARCH
save_env SUFFIX
save_env NAME

cat > ben/apt-ftparchive.conf <<EOF
APT::FTPArchive::Release {
        Origin "$ORIGIN";
        Label "$LABEL";
        Suite "$SUITE";
        Architectures "source $ARCH";
        Description "Debian packages rebuilt for transition $NAME";
};
EOF

cat > ben/download.ben <<EOF
mirror = "$MIRROR";
suite = "unstable";
areas = [ "main"; "contrib"; "non-free"; "non-free-firmware" ];

architectures = [
    "$ARCH"
];
EOF

cat > ben/rebuild.ben <<EOF
architectures = [ "$ARCH" ];

EOF
cat "$CONFIG/rebuild.ben" >> ben/rebuild.ben

if [ -f "$CONFIG/filter.txt" ]; then
    cp "$CONFIG/filter.txt" ben
fi

cp "$CONFIG/index.html.in" ben

touch pool/stamp
make pool

if ! [ -f ben/rootfs.tar.zst ]; then
    usr/lib/create-rootfs.sh
fi
