#!/bin/sh
# Copyright 2010 Novell, Inc.
# Author: Peter Bowen <pzb@novell.com> as a work made for hire
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License 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.
#
# /etc/init.d/amazon
#
#   and it's symbolic link
#
# /usr/sbin/rcamazon
#
# chkconfig: 345 90 10
# description: Configure an EC2 instance on boot.  Includes generating a SSH \
# host key, adding the instance key into the root keyring,
# installing the latest EC2 AMI tools, and randomizing \
# the root password on first boot of the instance.
#
### BEGIN INIT INFO
# Provides:       amazon
# Required-Start: $network $remote_fs $syslog
# Should-Start:   sces-client
# Required-Stop:  $null
# Should-Stop:    $null
# Default-Start:  3 5
# Default-Stop: 
# Description:    Fetch ec2 certificates    
# Short-Description: Fetch ec2 certificates 
# X-UnitedLinux-Default-Enabled: yes
### END INIT INFO

. /etc/rc.status
[ -r /etc/sysconfig/amazon ] && . /etc/sysconfig/amazon

# First reset status of this service
rc_reset

# We need the etc settings directory
if [ ! -d /etc/ec2 ]; then
    mkdir -p /etc/ec2
fi
##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"
}

# Did we already configure our instance?
# Find out and update the stored instance ID if needed
##function: isConfigured
function isConfigured {
    local instanceFile=/etc/ec2/instance
    instanceId=$(ec2_meta_data instance-id 1.0)
    if [ -f $instanceFile ]; then
        oldInstance=$(<$instanceFile)
        if [ "$oldInstance" == "$instanceId" ]; then
            return 0
        fi
    fi
    echo "$instanceId" > /etc/ec2/instance
    return 1
}   

# Checks to see if a file is older than 5 minutes
# Files are not old if they do not exist
##function: oldFile
function oldFile {
    tocheck=$1
    if [ ! -f "$tocheck" ]; then
        return 1
    fi
    then=$(stat -c '%Z' "$tocheck")
    now=$(date '+%s')
    since=$(( $now - $then))
    if [ $since -gt 300 ]; then
        return 0
    else
        return 1
    fi
}

##function: resetSSHkeys
function resetSSHkeys {
    keyReset=1
    if oldFile /etc/ssh/ssh_host_key; then
        echo "Regenerating /etc/ssh/ssh_host_key"
        rm -f /etc/ssh/ssh_host_key
        ssh-keygen -t rsa1 -b 1024 -f /etc/ssh/ssh_host_key -N ''
        keyReset=0
    fi
    if oldFile /etc/ssh/ssh_host_dsa_key; then
        echo "Regenerating /etc/ssh/ssh_host_dsa_key"
        rm -f /etc/ssh/ssh_host_dsa_key
        ssh-keygen -t dsa -b 1024 -f /etc/ssh/ssh_host_dsa_key -N ''
        keyReset=0
    fi
    if oldFile /etc/ssh/ssh_host_rsa_key; then
        echo "Regenerating /etc/ssh/ssh_host_rsa_key"
        rm -f /etc/ssh/ssh_host_rsa_key
        ssh-keygen -t rsa -b 1024 -f /etc/ssh/ssh_host_rsa_key -N ''
        keyReset=0
    fi
    return $keyReset
}

##function: restartSSHD
function restartSSHD {
    serviceOpts=$(service sshd help)
    useOpt="restart"
    echo "$serviceOpts" | grep -F -q try-restart
    if [ $? -eq 0 ]; then
        useOpt="try-restart"
    fi
    echo "$serviceOpts" | grep -F -q condrestart
    if [ $? -eq 0 ]; then
        useOpt="condrestart"
    fi
    service sshd "$useOpt"
}

case "$1" in
    start)
        if ! isConfigured; then
            if [ "$EC2_RANDOM_ROOTPW" != "no" ]; then
                echo "Randomizing root password"
                head -c 200 /dev/urandom | tr -cd '[:graph:]' | head -c 40 | passwd --stdin root
            fi
            if [ "$EC2_RESET_SSH_KEYS" != "no" ]; then
                echo "Checking for SSH host key freshness"
                resetSSHkeys && restartSSHD
            fi
            if [ "$EC2_PROCESS_USERDATA" == "yes" ]; then
                echo "Processing instance user-data"
                ec2-handle-userdata
            fi
            if [ -f /var/lib/zypp/AnonymousUniqueId -a $(type -p uuidgen) ]; then
                uuidgen > /var/lib/zypp/AnonymousUniqueId
            fi
            if [ "$EC2_RESET_NTP_KEY" != "no" -a -f /etc/ntp.keys ]; then
                newkey=$(LC_CTYPE=C tr -cd 'a-f0-9' </dev/urandom | head -c 7)
                echo "1 M $newkey" > /etc/ntp.keys
            fi
        fi
        if [ "$EC2_LOAD_KEYS" != "no" ]; then
            echo "Fetching User SSH key..."
            ec2-get-credentials
        fi
        # The flag says that the initrd should be rebuilt
        # usually because it was built in a different environment, and
        # we want to optimize it for the running system
        if [ -e /boot/.rebuild-initrd ]; then
            mkinitrd
            [ $? -eq 0 ] && rm -f /boot/.rebuild-initrd
        fi
        if [ "$EC2_REWRITE_UPDATE_URLS" != "no" ]; then
            echo "Update repository configuration..."
            suse-ec2-update-repos
        fi
        if [ "$EC2_UPDATE_AMI_TOOLS" != "no" ]; then
            echo "Updating AMI tools..."
            ec2-update-tools
        fi
        if [ "$EC2_INSTALL_TESLA" != "no" ]; then
            suse-ec2-install-tesla
        fi
        rc_status -v
        ;;
    stop)
        true
        rc_status -v
        ;;
    try-restart)
        $0 status >/dev/null &&  $0 restart
        rc_status
        ;;
    reload)
        ;;
    restart)
        $0 stop
        $0 start
        rc_status
        ;;
    *)
        echo "Usage: $0 {start|stop|try-restart|restart}"
        exit 1
        ;;
esac
rc_exit

