#!/bin/bash
# Copyright 2010 Novell, Inc.
# Copyright 2008 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# Licensed under the Amazon Software License (the "License").
#
# You may not use this file except in compliance with the License. A copy of
# the License is located at http://aws.amazon.com/asl or in the
# "AMAZON-LICENSE" file accompanying this file.
#
# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.

##private function: cleanup
function cleanup {
  [ "$PUB_KEY_FROM_HTTP" -a -f "$PUB_KEY_FROM_HTTP" ] && rm -f "$PUB_KEY_FROM_HTTP"
}

trap cleanup INT TERM

##function: ec2_instance_data
ec2_instance_data() {
  local ver="latest"
  [ "$2" ] && ver="$2"
  curl --retry 3 --retry-delay 0 --silent --fail "http://169.254.169.254/$ver/$1"
  [ $? -eq 0 ] && echo
}

##function: ec2_meta_data
ec2_meta_data() {
  ec2_instance_data "meta-data/$1" "$2"
}

PUB_KEY_FROM_HTTP=$(mktemp)
ROOT_AUTHORIZED_KEYS=/root/.ssh/authorized_keys

# We need somewhere to put the keys.
ROOTAK_DIR=$(dirname "$ROOT_AUTHORIZED_KEYS")
if [ ! -d "$ROOTAK_DIR" ] ; then
    mkdir -p "$ROOTAK_DIR" 
    chmod 0700 "$ROOTAK_DIR"
fi

# Fetch credentials from meta-data
if [ ! -f "$PUB_KEY_FROM_HTTP" ]; then 
	echo "Failed to create temporary file for SSH key"|logger -s -t "ec2"
    cleanup
    exit 1
fi

ec2_meta_data public-keys/0/openssh-key 1.0 > "$PUB_KEY_FROM_HTTP" 
if [ $? -eq 0 -a -s "$PUB_KEY_FROM_HTTP" ] ; then
	if ! grep -F -q -f "$PUB_KEY_FROM_HTTP" "$ROOT_AUTHORIZED_KEYS" 2>/dev/null; then
   		cat "$PUB_KEY_FROM_HTTP" >> "$ROOT_AUTHORIZED_KEYS"
   		echo "New key added to authorized keys file from parameters"|logger -s -t "ec2"
    else
        echo "Already have your key"|logger -s -t "ec2"
   	fi
fi

if [ ! -f $ROOT_AUTHORIZED_KEYS ]; then
        echo "*!*!*! FATAL ERROR *!*!*! Not able to find authorized_keys file [$ROOT_AUTHORIZED_KEYS]"|logger -s -t "ec2"
else
  		chmod 0600 "$ROOT_AUTHORIZED_KEYS"
fi
cleanup

exit 0
