56 lines
1.6 KiB
Bash
Executable File
56 lines
1.6 KiB
Bash
Executable File
#!/bin/bash
|
|
|
|
# Extract the login details from enpass
|
|
LABS=$(enpasscli -vault="$HOME/Documents/Enpass/Vaults/primary" -sort show "Scarif: Labs" 2>&1)
|
|
LABSUN=$(echo "$LABS" | grep -Po "(?<=login: )\w+")
|
|
LABSPW=$(echo "$LABS" | grep -Po "(?<=pass : ).+(?=\")")
|
|
|
|
SSHPATH="$HOME/.ssh/id_ed25519" # The path to the SSH key file
|
|
TITLE="$USER@$(cat /etc/hostname)" # The title for the SSH key
|
|
|
|
# Generate the SSH key if it does not exist
|
|
if [ ! -f $SSHPATH ] && ssh-keygen -t ed25519 -f "$SSHPATH" -N "" -q
|
|
|
|
# A method to generate the parameters for creating an SSH key on gitea
|
|
generate_post_data() {
|
|
cat <<EOF
|
|
{
|
|
"key": "$(cat "$SSHPATH.pub")",
|
|
"read_only": false,
|
|
"title": "$TITLE"
|
|
}
|
|
EOF
|
|
}
|
|
|
|
CREDENTIALS="$LABSUN:$LABSPW" # The credentials to pass to the API
|
|
KEYS_URL="https://$CREDENTIALS@labs.scarif.space/api/v1/users/keys"
|
|
|
|
# Get all the existing keys
|
|
KEYS=$(curl -X GET -s --url "$KEYS_URL")
|
|
|
|
KEY_EXISTS=$(echo $KEYS | jq --arg KEY "$(cat "$SSHPATH.pub")" 'contains({ key: $KEY })')
|
|
|
|
[[ $KEY_EXISTS == true ]] && return
|
|
|
|
# Extract the ids of the keys with the same title as this machine
|
|
IDS=$(echo $KEYS | jq --arg TITLE "$TITLE" 'map(select(.title == $TITLE))[].id')
|
|
|
|
# Loop through the keys and remove them from gitea to be replaced by the new one
|
|
if [ ! -z "$IDS" ]; do
|
|
for ID in IDS; do
|
|
curl -X DELETE \
|
|
-s \
|
|
-H "Accept: application/json" \
|
|
-H "Content-Type:application/json" \
|
|
--url "$KEYS_URL/$ID"
|
|
done
|
|
fi
|
|
|
|
# Save the new key in gitea
|
|
curl -X POST \
|
|
-s \
|
|
-H "Accept: application/json" \
|
|
-H "Content-Type:application/json" \
|
|
--data "$(generate_post_data)" \
|
|
--url "$KEYS_URL"
|