#!/bin/bash

set -e  # Exit immediately if a command exits with a non-zero status

CERTIFICATE_PATH=$HOME/build_certificate.p12
PP_PATH=$HOME/build_pp.mobileprovision
KEYCHAIN_PATH=$HOME/app-signing.keychain-db

setup_certificates() {
    echo "Setting up certificates and provisioning profiles..."

    # Import certificate and provisioning profile from environment variables
    echo -n "$VERIFY_PASSKEYS_DEMO_CERT" | base64 --decode -o $CERTIFICATE_PATH
    echo -n "$VERIFY_PASSKEYS_DEMO_PROFILE" | base64 --decode -o $PP_PATH

    # Create temporary keychain
    security create-keychain -p "$VERIFY_PASSKEYS_DEMO_KEYCHAIN_PASS" $KEYCHAIN_PATH
    security set-keychain-settings -lut 21600 $KEYCHAIN_PATH
    security unlock-keychain -p "$VERIFY_PASSKEYS_DEMO_KEYCHAIN_PASS" $KEYCHAIN_PATH

    # Import certificate into keychain
    security import $CERTIFICATE_PATH -P "$VERIFY_PASSKEYS_DEMO_PASS" -A -t cert -f pkcs12 -k $KEYCHAIN_PATH
    security set-key-partition-list -S apple-tool:,apple: -k "$VERIFY_PASSKEYS_DEMO_KEYCHAIN_PASS" $KEYCHAIN_PATH
    security list-keychain -d user -s $KEYCHAIN_PATH

    # Apply provisioning profile
    mkdir -p ~/Library/MobileDevice/Provisioning\ Profiles
    cp $PP_PATH ~/Library/MobileDevice/Provisioning\ Profiles

    echo "Certificates and provisioning profiles set up successfully."
}

cleanup_signing() {
    echo "Cleaning up keychain and provisioning profile..."

    security delete-keychain $KEYCHAIN_PATH || true
    rm -f ~/Library/MobileDevice/Provisioning\ Profiles/build_pp.mobileprovision || true

    echo "Cleanup completed."
}

# Run based on the argument passed to the script
case "$1" in
    setup)
        setup_certificates
        ;;
    cleanup)
        cleanup_signing
        ;;
    *)
        echo "Usage: $0 {setup|cleanup}"
        exit 1
        ;;
esac