#!/usr/bin/perl

use strict;

my $host = `hostname`;
chomp($host);
die "Wrong host" unless$host eq "repo.curiepoint.com";
die "Wrong user" unless $ENV{"USER"} eq "jenkins";

my $basedir = "/home/www/debian.bklabs.net";
my $distpath = $basedir."/dists/curiepoint";
my $prefix = "";
my @pools = ( "main", "stretch", "buster", "bullseye", "bookworm", "trixie");

foreach my $pool (@pools) {
    print "Doing $pool\n";
    scanpkgs($pool);
}

sub scanpkgs
{
    my $pool = shift;
    my $pooldir = "pool-".$pool;

    # Create pool dir if doesn't exist
    system("mkdir -p $distpath/$pool/binary-i386/");
    system("mkdir -p $distpath/$pool/binary-amd64/");

    # Remove old pkg files
    unlink("$distpath/$pool/binary-i386/Packages.gz");
    unlink("$distpath/$pool/binary-amd64/Packages.gz");

    # Generic i386
    system("dpkg-scanpackages -a i386 $pooldir /dev/null $prefix "
	   ." > $distpath/$pool/binary-i386/Packages");

    # amd64
    system("dpkg-scanpackages -a amd64 $pooldir /dev/null $prefix "
	   ." > $distpath/$pool/binary-amd64/Packages");

    # For non-main pool also include main data
    if ($pool ne "main") {
	# i386
	system("zcat $distpath/main/binary-i386/Packages.gz >> $distpath/$pool/binary-i386/Packages");
	# amd64
	system("zcat $distpath/main/binary-amd64/Packages.gz >> $distpath/$pool/binary-amd64/Packages");
    }

    # Compress files
    system("gzip -fk9 $distpath/$pool/binary-i386/Packages");
    system("gzip -fk9 $distpath/$pool/binary-amd64/Packages");

    # Build release files
    system("apt-ftparchive release -capt.conf $distpath > $distpath/Release");
    unlink("$distpath/InRelease");
    system("gpg -u debian\@curiepoint.com --clearsign -o $distpath/InRelease $distpath/Release");
    unlink("$distpath/Release.gpg");
    system("gpg -u debian\@curiepoint.com -abs -o $distpath/Release.gpg $distpath/Release")
}
