#!/bin/bash
#Importing gpg key via cli
#https://d.sb/2016/11/gpg-inappropriate-ioctl-for-device-errors
FILE="$1"
GPG_KEY="$2"
GPG_PASS="$3"

GPG_DIR="/root/.gnupg"
mkdir -p "$GPG_DIR"

if [[ -f "$GPG_KEY" ]]; then
    GPG_KEY=$(cat "$GPG_KEY")
fi

#Trim single quotes if it has any. (Single quotes are needed for ACT)
GPG_KEY=$(echo "$GPG_KEY" | tr -d \')

gpg --homedir "$GPG_DIR" --allow-secret-key-import --import --batch --passphrase "$GPG_PASS" <<EOF
$GPG_KEY
EOF

gpg --homedir "$GPG_DIR" --list-keys
#Get name with email, then cut it to get just the name.
SIGNER_NAME=$(gpg --homedir "$GPG_DIR" --with-colons --list-keys | grep uid: | cut -d ':' -f 10 | cut -d '<' -f 1 | xargs)

rpmsign --define "_gpg_name $SIGNER_NAME" --define "_gpg_sign_cmd_extra_args --homedir $GPG_DIR --pinentry-mode loopback --passphrase $GPG_PASS" --addsign "$FILE"

SIGNER=$(rpm -qpi simbaspark-2.6.29.1049-1.x86_64.rpm | grep "Signature" | cut -d ':' -f 2 | xargs)
RESULT=$?
if [[ "$SIGNER" == "(none)" ]]; then
    RESULT=1
fi

#Set the public key as output.
PUBLIC_KEY=$(gpg --homedir "$GPG_DIR" --armor --export "$SIGNER_NAME")
PUBLIC_KEY="${PUBLIC_KEY//'%'/'%25'}"
PUBLIC_KEY="${PUBLIC_KEY//$'\n'/'%0A'}"
PUBLIC_KEY="${PUBLIC_KEY//$'\r'/'%0D'}"
echo "publicKey=$PUBLIC_KEY" >> "$GITHUB_OUTPUT"

exit $RESULT
