#!/bin/bash

# This script generates an updated apt repository based on the .deb files required for ARC-EX. For reference, please refer to https://earthly.dev/blog/creating-and-hosting-your-own-deb-packages-and-apt-repo/

BASE_PATH=/home/fwdev/arc-ex-packages

rm -r $BASE_PATH/arc-ex-libs/dists/
mkdir -p $BASE_PATH/arc-ex-libs/dists/stable/main/binary-amd64

# Generate and compress a packages file
cd $BASE_PATH/arc-ex-libs/
dpkg-scanpackages -m --arch amd64 pool/ > dists/stable/main/binary-amd64/Packages
cat dists/stable/main/binary-amd64/Packages | gzip -9 > dists/stable/main/binary-amd64/Packages.gz

# Generate a Release file
cd $BASE_PATH/arc-ex-libs/dists/stable
sh $BASE_PATH/generate-apt-release-file.sh > Release 
cd $BASE_PATH

# Delete the previous keys from the keystore
rm -r $BASE_PATH/apt-key-store > /dev/null 2>&1
mkdir $BASE_PATH/apt-key-store

# Sign the repository by signing the Release file
echo "%echo Generating an arc-ex PGP key
Key-Type: RSA
Key-Length: 4096
Name-Real: fwdev
Name-Email: fwdevelopment@onwd.com
Expire-Date: 0
%no-ask-passphrase
%no-protection
%commit" > /tmp/arc-ex-pgp-key.batch

export GNUPGHOME="$(mktemp -d $BASE_PATH/apt-key-store/pgpkeys-XXXXXX)"
gpg --no-tty --batch --gen-key /tmp/arc-ex-pgp-key.batch

# Export the public key 
gpg --armor --export 'fwdevelopment@onwd.com' arc-ex > $BASE_PATH/apt-key-store/pgp-key.public

# Export the private key
gpg --armor --export-secret-keys 'fwdevelopment@onwd.com' arc-ex > $BASE_PATH/apt-key-store/pgp-key.private
export GNUPGHOME="$(mktemp -d $BASE_PATH/apt-key-store/pgpkeys-XXXXXX)"

# Import backed-up private key
cat $BASE_PATH/apt-key-store/pgp-key.private | gpg --import

# Now sign the release file
cat $BASE_PATH/arc-ex-libs/dists/stable/Release | gpg --default-key arc-ex -abs > $BASE_PATH/arc-ex-libs/dists/stable/Release.gpg

# Combine the contents of Release and the PGP signature into a single file to speed things up for clients.
cat $BASE_PATH/arc-ex-libs/dists/stable/Release | gpg --default-key arc-ex -abs --clearsign > $BASE_PATH/arc-ex-libs/dists/stable/InRelease

