#!/bin/bash
# Copyright 2010 Novell, Inc.
# Author: Peter Bowen <pzb@novell.com> as a work made for hire.
#
# This work is licensed under the 
# Creative Commons Attribution-ShareAlike 3.0 Unported License. 
# To view a copy of this license, visit 
# http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to 
# Creative Commons, 171 Second Street, Suite 300, 
# San Francisco, California, 94105, USA.
#

if [ ! -r /etc/sces/validation.token ]; then
    [ "$ACTIVATE" ] && exec $ACTIVATE
    exit 1
fi

##function: isValidHost
function isValidHost
{
  getent hosts "$1" &>/dev/null
}

##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"
}

##function: ec2-region
function ec2-region() {
    local az=$(ec2-meta-data placement/availability-zone 2008-02-01)
    if [ "$az" ]; then
        echo ${az%?}
    else
        echo "default"
    fi
}

function sysconfig_get_key() {
    S='[[:space:]]*'
    grep -E "^$S$2$S=$S" "$1" | sed -e "s/^$S$2$S=$S//;s/$S\$//;s/^\"//;s/\"\$//"
}

##function: system_flavour
function system_flavour() {
    local sf=/etc/sysconfig/sces
    if [ ! -f $sf -o ! -s $sf ]; then
        echo
        return
    fi
    echo -n -
    sysconfig_get_key $sf SCES_FLAVOUR | head -n 1
}

# Note, the result of the function is not verified
##function find-reg-host
function find-reg-host() {
    local region=$(ec2-region)
    local flavour=$(system_flavour)
    local rhost="default-ec2-reg$flavour.$SCES_DOMAIN_NAME"
    isValidHost "${region}-ec2-reg$flavour.$SCES_DOMAIN_NAME"
    if [ $? -eq 0 ]; then
      rhost="${region}-ec2-reg$flavour.$SCES_DOMAIN_NAME"
    fi
    # No HTTPS, because ELB+HTTPS has issues
    local ts=$(date +'%s')
    local realhost=$(curl --location --retry 3 --retry-delay 0 --silent --fail "http://$rhost/2010-08-29/ec2/findreghost?ts=$ts")
    [ $? -eq 0 ] && echo "$realhost"
}

if [ -f /etc/sysconfig/sces ]; then
    SCES_DOMAIN_NAME=$(sysconfig_get_key /etc/sysconfig/sces SCES_DOMAIN_NAME)
fi
[ "$SCES_DOMAIN_NAME" ] || SCES_DOMAIN_NAME="susecloud.net"

RETRIES=2

for n in $(seq 1 $RETRIES); do
    REGHOST=$(find-reg-host)
    curl --location --retry 2 --retry-delay 0 --silent --fail --header 'Content-Type: text/plain' \
      --data-binary @/etc/sces/validation.token "https://$REGHOST/2010-08-29/ec2/deactivate"

    if [ $? -eq 0 ]; then
        break
    fi

    if [ $n -eq $RETRIES ]; then
        exit 2
    fi
done

exit 0
