#!/bin/sh
### BEGIN INIT INFO
# Provides:          ec2-ssh-key        
# Required-Start:    vyatta-router
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Grab ssh keys from Amazon EC2 server
### END INIT INFO
PATH=/sbin:/usr/sbin:/bin:/usr/bin

. /lib/init/vars.sh
. /lib/lsb/init-functions

# To set the config values
: /etc/default/vyatta
source /etc/default/vyatta

do_start() {
  if [ ! -d /home/vyatta/.ssh ] ; then
          mkdir -p /home/vyatta/.ssh
          chmod 700 /home/vyatta/.ssh
  fi
  # Fetch public key using HTTP
  /usr/bin/curl -f http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key > /tmp/my-key
  if [ $? -eq 0 ] ; then
          log_action_msg "Copied ssh key for user "vyatta" from ec2" >&2
          sg vyattacfg -c "/opt/vyatta/sbin/vyatta_config_ssh"
          rm /tmp/my-key
  else
         log_action_msg "No ssh key for user "vyatta" from ec2" >&2
         sg vyattacfg -c "/opt/vyatta/sbin/vyatta_config_ssh"

  fi
  # or fetch public key using the file in the ephemeral store:
  if [ -e /mnt/openssh_id.pub ] ; then
          cat /mnt/openssh_id.pub >> /home/vyatta/.ssh/authorized_keys
          chmod 600 /home/vyatta/.ssh/authorized_keys
  fi
}

case "$1" in
    start)
        log_action_msg "Requesting vyatta ssh keys from ec2" >&2
        do_start
        ;;
    restart|reload|force-reload)
        log_action_msg "Error: argument '$1' not supported" >&2
        exit 3
        ;;
    stop)
        ;;
    *)
        echo "Usage: $0 start|stop" >&2
        exit 3
        ;;
esac
