#!/bin/bash

if [ "$#" -lt 4 ]; then
        echo "Usage: $0 <signing key(p12)> <passphrase> <source_directory> <output_directory>" && exit 1
fi

CRED="$1"
PSK="$2"
SRC_DIR="$3"
OUT_DIR="$4"

# Validate source directory exists
if [ ! -d "$SRC_DIR" ]; then
        echo "Error: Source directory '$SRC_DIR' does not exist" && exit 1
fi

# Create output directory if it doesn't exist
mkdir -p "$OUT_DIR"
if [ $? -ne 0 ]; then
        echo "Error: Failed to create output directory '$OUT_DIR'" && exit 1
fi

# Find all *.bolt packages in source directory
PKGS=("$SRC_DIR"/*.bolt)

# Check if any .bolt files were found
if [ ! -e "${PKGS[0]}" ]; then
        echo "Error: No *.bolt packages found in '$SRC_DIR'" && exit 1
fi

echo "Found ${#PKGS[@]} package(s) to sign"
echo "Output directory: $OUT_DIR"
echo ""

# Get absolute path of credentials file
CRED=$(realpath "$CRED")

for pkg in "${PKGS[@]}"; do
        pkg_name=$(basename "$pkg")
        echo "Signing $pkg_name..."
        
        # Copy package to output directory
        cp "$pkg" "$OUT_DIR/$pkg_name"
        if [ $? -ne 0 ]; then
                echo "Error: Failed to copy $pkg_name to output directory" && exit 1
        fi
        
        # Sign the package in the output directory
        cd "$OUT_DIR"
        ralfpack sign --pkcs12="$CRED" --passphrase="$PSK" "$pkg_name"
        if [ $? -eq 0 ]; then
                echo "Success..."
                cd - > /dev/null
        else
                echo "Failed; aborting" && exit 1
        fi
done

echo ""
echo "All packages signed successfully!"
echo "Signed packages are in: $OUT_DIR"
