#!/usr/bin/env bash
# Script to verify cosign signatures for chainver releases
# This verifies the checksums.txt signature, then uses it to verify individual artifacts

set -euo pipefail

ARTIFACT=${1:-}

# Detect if we're in a chainver package directory structure
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ -d "$SCRIPT_DIR/signatures" ] && [ -d "$SCRIPT_DIR/archives" ]; then
    # We're in the package root directory
    SIGNATURES_DIR="$SCRIPT_DIR/signatures"
    ARCHIVES_DIR="$SCRIPT_DIR/archives"
elif [ -d "$SCRIPT_DIR/../signatures" ] && [ -d "$SCRIPT_DIR/../archives" ]; then
    # Script is in a subdirectory (like scripts/)
    SIGNATURES_DIR="$SCRIPT_DIR/../signatures"
    ARCHIVES_DIR="$SCRIPT_DIR/../archives"
else
    # Use current directory (backward compatibility)
    SIGNATURES_DIR="."
    ARCHIVES_DIR="."
fi

if [ -z "$ARTIFACT" ]; then
    echo "Usage: $0 <artifact-file>"
    echo "Example: $0 chainver_1.2.3_Linux_x86_64.tar.gz"
    echo ""
    echo "This script verifies chainver artifacts using signed checksums."
    echo ""
    if [ "$SIGNATURES_DIR" != "." ]; then
        echo "Available artifacts in $ARCHIVES_DIR:"
        ls -1 "$ARCHIVES_DIR" | grep -E '\.(tar\.gz|zip)$' | sed 's/^/  - /'
    fi
    exit 1
fi

# If artifact is just a filename, look for it in archives directory
if [ ! -f "$ARTIFACT" ] && [ -f "$ARCHIVES_DIR/$ARTIFACT" ]; then
    ARTIFACT="$ARCHIVES_DIR/$ARTIFACT"
fi

# First, verify the checksums.txt signature
if [ ! -f "$SIGNATURES_DIR/checksums.txt" ]; then
    echo "Error: checksums.txt not found in $SIGNATURES_DIR"
    echo "Please ensure you have the complete chainver package"
    exit 1
fi

if [ ! -f "$SIGNATURES_DIR/checksums.txt.sig" ]; then
    echo "Error: checksums.txt.sig not found in $SIGNATURES_DIR"
    exit 1
fi

if [ ! -f "$SIGNATURES_DIR/checksums.txt.cert.pem" ]; then
    echo "Error: checksums.txt.cert.pem not found in $SIGNATURES_DIR"
    exit 1
fi

echo "Verifying checksums.txt signature..."

# Verify the checksums.txt signature
cosign verify-blob \
    --certificate "$SIGNATURES_DIR/checksums.txt.cert.pem" \
    --signature "$SIGNATURES_DIR/checksums.txt.sig" \
    --certificate-identity-regexp "https://github.com/chainguard-dev/chainver/*" \
    --certificate-oidc-issuer "https://token.actions.githubusercontent.com" \
    "$SIGNATURES_DIR/checksums.txt"

echo ""
echo "Certificate details:"
# Handle both PEM and base64-encoded certificates
if grep -q "BEGIN CERTIFICATE" "$SIGNATURES_DIR/checksums.txt.cert.pem" 2>/dev/null; then
    openssl x509 -in "$SIGNATURES_DIR/checksums.txt.cert.pem" -text -noout | grep -E "(Subject:|Issuer:|Not Before:|Not After:|URI:)" || true
else
    cat "$SIGNATURES_DIR/checksums.txt.cert.pem" | base64 -d | openssl x509 -text -noout | grep -E "(Subject:|Issuer:|Not Before:|Not After:|URI:)" || true
fi

echo "✅ Checksums signature verified successfully!"

# Now verify the artifact checksum if an artifact was specified
if [ -n "$ARTIFACT" ] && [ -f "$ARTIFACT" ]; then
    echo ""
    echo "Verifying $(basename "$ARTIFACT") checksum..."
    
    # Create a temporary directory for verification
    TEMP_DIR=$(mktemp -d)
    trap "rm -rf $TEMP_DIR" EXIT
    
    # Copy checksums and artifact to temp dir
    cp "$SIGNATURES_DIR/checksums.txt" "$TEMP_DIR/"
    cp "$ARTIFACT" "$TEMP_DIR/$(basename "$ARTIFACT")"
    
    # Change to temp dir for verification
    cd "$TEMP_DIR"
    
    if command -v sha256sum >/dev/null 2>&1; then
        if sha256sum -c --ignore-missing checksums.txt 2>/dev/null | grep -q "$(basename "$ARTIFACT"): OK"; then
            echo "✅ Checksum verified successfully!"
        else
            echo "❌ Checksum verification failed!"
            exit 1
        fi
    else
        # macOS
        if shasum -a 256 -c checksums.txt 2>/dev/null | grep -q "$(basename "$ARTIFACT"): OK"; then
            echo "✅ Checksum verified successfully!"
        else
            echo "❌ Checksum verification failed!"
            exit 1
        fi
    fi
else
    echo ""
    echo "No artifact specified or file not found. Skipping artifact verification."
    if [ "$ARCHIVES_DIR" != "." ]; then
        echo "To verify an artifact, run:"
        echo "  $0 <artifact-filename>"
        echo ""
        echo "Available artifacts:"
        ls -1 "$ARCHIVES_DIR" | grep -E '\.(tar\.gz|zip)$' | sed 's/^/  /'
    fi
fi

echo ""
echo "Note: This verification confirms that:"
echo "  - The checksums file was signed by GitHub Actions"
echo "  - The signature is valid and matches the checksums"
echo "  - The signing certificate was issued by Fulcio"
if [ -n "$ARTIFACT" ] && [ -f "$ARTIFACT" ]; then
echo "  - The artifact matches its expected checksum"
fi