#!/bin/bash

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 repo/pool repo/conf repo/dists/rebuilt 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
save_env BASE_SUITE
save_env SOURCE_SUITE
save_env URL_PREFIX

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

cat > repo/conf/mk-release.sh <<EOF
#!/bin/bash

set -e

cd "\$(dirname \$0)/.."

if ! [ -d pool ]; then
   echo "Unexpected layout!"
   exit 1
fi

rm -rf dists/rebuilt
mkdir -p dists/rebuilt/main/{source,binary-$ARCH}
dpkg-scanpackages pool > dists/rebuilt/main/binary-$ARCH/Packages
dpkg-scansources pool > dists/rebuilt/main/source/Sources
apt-ftparchive -c conf/apt-ftparchive.conf release dists/rebuilt > dists/rebuilt/Release
EOF
chmod +x repo/conf/mk-release.sh

cat > ben/download.ben <<EOF
mirror = "$MIRROR";
suite = "$SOURCE_SUITE";
components = auto;

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

repo/conf/mk-release.sh

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