name: 'Configure Apple Certificate'
description: 'Configures a P12 certificate into the keychain for signing'
inputs:
  certificate-value:
    description: 'A base64 encoded string representing the p12 value of the certificate.'
    required: true
    default: ''

  certificate-password:  
    description: 'The password for the certificate'
    required: true
    default: ''

  keychain:
    description: 'The name of the keychain to install the certificate into'
    required: true
    default: ''
  
  keychain-pw:
    description: 'The password to use for the keychain'
    required: true
    default: '' 

  certificate-file:
    description: 'Intermediary name for p12 file'
    required: false
    default: 'certificate.p12'


runs:
  using: "composite"
  steps: 
     - name: Add Installer Cert
       run: |
      
            # Recreate the certificate from the secure environment variable
            echo ${{ inputs.certificate-value }} | base64 --decode > ${{ inputs.certificate-file }}

            if [[ $( security list-keychain | grep -c ${{ inputs.keychain }} ) -eq 0 ]]; then

               #create a keychain
               security create-keychain -p ${{ inputs.keychain-pw }} ${{ inputs.keychain }}

               # add the keychain to the search list so others may see it
               security list-keychains -s `security list-keychains | xargs` ${{ inputs.keychain }}

               # Make the keychain the default so identities are found
               security default-keychain -s ${{ inputs.keychain }}
            fi

            # Unlock the keychain
            security unlock-keychain -p ${{ inputs.keychain-pw }} ${{ inputs.keychain }}
            
            # Extend the relock timeout
            security set-keychain-settings -lut 7200 ${{ inputs.keychain }}

            # Add certificate to keychain
            security import ${{ inputs.certificate-file }} -k ${{ inputs.keychain }} -P ${{ inputs.certificate-password }} -T /usr/bin/productsign -T /usr/bin/codesign

            # Enable codesigning from non-user interactive shell
            security set-key-partition-list -S apple-tool:,apple: -s -k ${{ inputs.keychain-pw }} -t private ${{ inputs.keychain }}
            
            # remove certs
            rm -fr *.p12
            rm -rf *.cer
       
       shell: bash


