#!/bin/bash
# description "fetch SSH keys"
# author "Scaleway <opensource@scaleway.com>"

set -e

if ! /usr/bin/scw-metadata --cached > /dev/null 2>&1; then
    echo "Error: could not retrieve metadata." >&1
    exit 1
fi

# ensure /root/.ssh exists and has correct permissions
mkdir -p /root/.ssh
chmod 700 /root/.ssh

# ensure /root has the correct permissions
chown root:root /root
chmod 700 /root

# `--upgrade` refreshes the metadata cache
if [ "$1" = "--upgrade" ]; then
    /usr/bin/scw-metadata > /dev/null 2>&1
fi

cat << EOF > /root/.ssh/authorized_keys.new
#
# WARNING: Automatically generated file
# This file will be erased at every boot
# This file was generated with '/usr/sbin/scw-fetch-ssh-keys'
#
# To add a new key, you can:
#   -- Add keys in your Scaleway project: https://console.scaleway.com/project/ssh-keys
#   -- Add keys using server tags: https://console.scaleway.com/instance/servers/$(/usr/bin/scw-metadata --cached ZONE)/$(/usr/bin/scw-metadata --cached ID)/overview
#        - i.e: "AUTHORIZED_KEY=ssh-rsa_XXXXXXXXXXX AUTHORIZED_KEY=ssh-rsa_YYYYYYYYYYYYYYY"
#        - Be sure to replace all spaces with underscores
#        - $> sed 's/ /_/g' ~/.ssh/id_rsa.pub
#   -- Add the keys to '/root/.ssh/instance_keys' which will be imported
#
# And recreate your 'authorized_keys' file with the new keys:
#   -- Run 'scw-fetch-ssh-keys --upgrade'
#
EOF

# authorized_keys should only be readable by the owner and no one else
chmod 0600 /root/.ssh/authorized_keys.new

# add Scaleway account keys
/usr/bin/scw-metadata --cached | grep SSH_PUBLIC_KEYS_.*_KEY | cut -d'=' -f 2- | tr -d \' >> /root/.ssh/authorized_keys.new

# add Server tags keys
/usr/bin/scw-metadata --cached | grep TAGS_.*=AUTHORIZED_KEY | cut -d'=' -f 3- | sed 's/_/\ /g' >> /root/.ssh/authorized_keys.new

# Import custom keys
if [ -f /root/.ssh/instance_keys ]; then
    cat << EOF >> /root/.ssh/authorized_keys.new
# Below your custom ssh keys from '/root/.ssh/instance_keys'
EOF
    (cat /root/.ssh/instance_keys | grep -v "^#" || true) >> /root/.ssh/authorized_keys.new
fi

# replace the existing file atomically
mv /root/.ssh/authorized_keys.new /root/.ssh/authorized_keys
