#!/bin/bash

set -e

URL_PREFIX="http://metadata/computeMetadata/v1beta1/"

update_keys() {
    local id="$1"
    local url="${URL_PREFIX}${id}/attributes/sshKeys"

    # The key may have a username: prerix which must be stripped
    local keys=$(curl --fail -s "$url" | sed -re 's/^\w*://')
    if [[ -n "$keys" ]]; then
        update-ssh-keys -a "gce-$id" <<<"$keys"
    fi
}

block-until-url "$URL_PREFIX"
# Generally sshKeys is only defined per-project
# but might as well support per-instance too.
update_keys project
update_keys instance
