#!/bin/bash

# --- Configuration ---
REPO_DIR="/repo/amos64"
OUT_DIR="/repo/amos64-signed"
IMA_KEY="${IMA_KEY:-/root/kernel-keys/ima-signing.pem}"
MAKEPKG_CMD="/sbin/makepkg"

# Ensure output directory exists
mkdir -p "$OUT_DIR"

# Find all .txz packages in the repo
find "$REPO_DIR" -type f -name "*.txz" | while read -r pkg; do
    echo "=================================================="
    echo "Processing: $pkg"
    
    # Calculate the relative path (e.g., a/acl-2.4.0-x86_64-2.txz)
    rel_path="${pkg#$REPO_DIR/}"
    rel_dir=$(dirname "$rel_path")
    
    # Create the corresponding series directory in the output folder
    mkdir -p "$OUT_DIR/$rel_dir"
    
    # Define the final output file path
    outfile="$OUT_DIR/$rel_path"
    
    # Create a temporary directory for extraction
    tmpdir=$(mktemp -d)
    
    # Extract using bsdtar to preserve xattrs without GNU tar warnings
    bsdtar -xf "$pkg" -C "$tmpdir" 2>/dev/null
    
    # Check if extraction succeeded
    if [ $? -ne 0 ]; then
        echo "ERROR: Failed to extract $pkg"
        rm -rf "$tmpdir"
        continue
    fi
    
    # Enter the directory and run makepkg
    (
        cd "$tmpdir" || exit 1
        
        # Run makepkg with IMA_KEY. 
        # -l y: Linkadd yes
        # -c n: Chown no
        IMA_KEY="$IMA_KEY" "$MAKEPKG_CMD" -l y -c n "$outfile"
    )
    
    if [ $? -ne 0 ]; then
        echo "ERROR: makepkg failed for $pkg"
    else
        echo "SUCCESS: Created $outfile"
    fi
    
    # Clean up the temp directory
    rm -rf "$tmpdir"
done