#! /bin/bash

QUIET=0
VERBOSE=0
ACCT_NAME=
DEST_TYPE=

parseArguments() {
  while [ "$1" != "" ] ; do
    case $1 in
      -v)
        VERBOSE=1
        ;;

      -q)
        QUIET=1
        ;;

      -a)
        ACCT_NAME=$2
        shift
        ;;

      -t)
        DEST_TYPE=$2
        if [ "$DEST_TYPE" == "GOOGLE" ] || [ "$DEST_TYPE" == "Google" ] ; then
            DEST_TYPE="google"
        fi
        if [ "$DEST_TYPE" != "google" ] ; then
            echo "Unsupported account type: $2"
            exit 1
        fi
        shift
        ;;

      -h | *)
        echo
        echo "Usage: $0 -a <account name> -t <account type> [-q][-v]"
        echo
        echo "Converts given account and corresponding pool to destination type if possible"
        echo
        echo "   -v                 Verbose"
        echo "   -q                 Quiet"
        echo "   -a <name>          Name of account to modify"
        echo "   -t <type>          New account type (e.g., \"google\")"
        echo "   -h                 This menu"
        echo
        echo "Example:"
        echo "  $0 -a my_account -t google"

        if [ "$1" == "-h" ] ; then
            exit 0
        fi
        exit 1
    esac

    shift
  done

  if [ "$ACCT_NAME" == "" ] ; then
    echo
    echo "  Error: -a flag must be supplied with a valid account name"
    echo
    exit 1
  fi

  if [ "$DEST_TYPE" == "" ] ; then
    echo
    echo "  Error: -t flag must be supplied with a valid account type (e.g., \"google\")"
    echo
    exit 1
  fi
}

log_verbose() {
  if [ "$VERBOSE" == "1" ] ; then
    log $*
  fi
}

log() {
  if [ "$QUIET" != "1" ] ; then
    echo $*
  fi
}

extract_gconfig_value() {
    _PARAM_GCONFIG_COLLECTION=$1
    _PARAM_GCONFIG_INDEX=$2
    _PARAM_GCONFIG_FIELD=$3

    GCONFIG_VALUE=`isi_gconfig -t cpool_cfg ${_PARAM_GCONFIG_COLLECTION}.${_PARAM_GCONFIG_INDEX}.${_PARAM_GCONFIG_FIELD} | awk -F "=" '{print $2}' | awk '{print $1}'`
}

update_pools_for() {
    _PARAM_ACCT_ID=$1
    _PARAM_ACCT_GUID=$2
    _PARAM_DEST_TYPE=$3

    log_verbose "Updating associated pools matching account_id ${_PARAM_ACCT_ID}, account_birth_cluster ${_PARAM_ACCT_GUID}"

    # First get a list of pools referencing the given account id
    ID_MATCHES=`isi_gconfig -t cpool_cfg | egrep "^provider_instance.*.account_ids.0.account_id \(uint32\) = ${_PARAM_ACCT_ID}" | awk -F "." '{print $2}' | xargs`

    # Narrow list of pool indices to those which also reference a matching birth_cluster_guid
    POOL_INDICES=
    for i in ${ID_MATCHES}; do
        POOL_INDICES+=" "`isi_gconfig -t cpool_cfg | egrep "^provider_instance.$i.account_ids.0.account_birth_cluster.*= ${_PARAM_ACCT_GUID}" | awk -F "." '{print $2}'`
    done

    # Update the pools and record the pool names along the way
    UPDATED_POOLS=""
    for i in ${POOL_INDICES}; do
        isi_gconfig -t cpool_cfg provider_instance.$i.type=${_PARAM_DEST_TYPE}
	isi_gconfig -t cpool_cfg provider_instance.${GCFG_INDEX}.last_update_date=`date -j "+%s"`000000

	extract_gconfig_value provider_instance $i provider_instance_name
	UPDATED_POOLS+=" $GCONFIG_VALUE"
	log_verbose "Updated pool $GCONFIG_VALUE"
    done
}

count_values() {
    NUM_VALUES=$#
}

get_friendly_account_type() {
    FRIENDLY_TYPE="$1"
    case $1 in
	CPT_GOOGLE_XML)
	    FRIENDLY_TYPE="Google"
	    ;;
	CPT_AZURE)
	    FRIENDLY_TYPE="Microsoft Azure"
	    ;;
	CPT_RAN)
	    FRIENDLY_TYPE="Isilon"
	    ;;
	CPT_AWS)
	    FRIENDLY_TYPE="Amazon S3"
	    ;;
	CPT_ECS)
	    FRIENDLY_TYPE="EMC ECS Appliance"
	    ;;
	CPT_ECS2)
	    FRIENDLY_TYPE="Virtustream Storage Cloud"
	    ;;
	CPT_AWS_C2S)
	    FRIENDLY_TYPE="Amazon C2S S3"
	    ;;
    esac
}

# Start
parseArguments $*

log_verbose "Attempting to convert account \"$ACCT_NAME\" to \"$DEST_TYPE\""

CLUSTER_STATE=`isi upgrade view | grep "Cluster Upgrade State" | awk -F ":" '{print $2}' | awk '{print $1}'`
if [ "$CLUSTER_STATE" != "committed" ] ; then
    echo "Cluster upgrade must be committed before proceeding (currently in \"$CLUSTER_STATE\")"
    exit 1
fi

# Get the gconfig index for the account
GCFG_INDEX=`isi_gconfig -t cpool_cfg | egrep "^account.*.account_name.*\b${ACCT_NAME}\$" | awk -F "." '{print $2}'`

# Should only get one match - otherwise, there's a problem in gconfig
count_values $GCFG_INDEX
if [ "$NUM_VALUES" == "0" ] ; then
    echo "Account ${ACCT_NAME} could not be found.  Aborting."
    exit 1
elif [ "$NUM_VALUES" != "1" ] ; then
    echo "Unexpected: More than one account with name ${ACCT_NAME} found.  Aborting."
    exit 1
fi

if [ "$?" != "0" ] || [ "$GCFG_INDEX" == "" ] ; then
    echo "Failed to find account ${ACCT_NAME}"
    exit 1
fi

log_verbose "Found $ACCT_NAME in gconfig at index $GCFG_INDEX"

# Grab existing gconfig values for id, cluster_guid and account type
extract_gconfig_value account ${GCFG_INDEX} birth_cluster_id
CLUS_GUID=$GCONFIG_VALUE

extract_gconfig_value account ${GCFG_INDEX} account_id
ACCT_ID=$GCONFIG_VALUE

extract_gconfig_value account ${GCFG_INDEX} ptype
OLD_ACCT_TYPE=$GCONFIG_VALUE

if [ "$OLD_ACCT_TYPE" != "CPT_ECS" ] ; then
    get_friendly_account_type $OLD_ACCT_TYPE
    echo "Cannot convert account type $FRIENDLY_TYPE to $DEST_TYPE"
    exit 1
fi

log_verbose "Old account type was $OLD_ACCT_TYPE.  Converting to $DEST_TYPE"

# Set new account type and make sure account is ok
isi_gconfig -t cpool_cfg account.${GCFG_INDEX}.ptype=CPT_GOOGLE_XML

NEW_STATE=`isi cloud accounts view ${ACCT_NAME} | grep State | grep -v Detail | awk -F ":" '{print $2}' | awk '{print $1}'`
if [ $NEW_STATE != "OK" ] ; then
    echo "After applying change, account state is $NEW_STATE.  Keep changes? (y/n)"
    read KEEP_CHANGES

    if [ "${KEEP_CHANGES:0:1}" != "y" ] && [ "${KEEP_CHANGES:0:1}" != "Y" ] ; then
        isi_gconfig -t cpool_cfg account.${GCFG_INDEX}.ptype=$OLD_ACCT_TYPE
        echo "Account changes reverted."
        exit 1
    fi
fi

# Touch the update time to make sure sync IQ sees the change
isi_gconfig -t cpool_cfg account.${GCFG_INDEX}.last_update_date=`date -j "+%s"`000000

# Update related pools
update_pools_for $ACCT_ID $CLUS_GUID CPT_GOOGLE_XML

log "Account $ACCT_NAME is now of type $DEST_TYPE.  Account state is $NEW_STATE."
if [ "$UPDATED_POOLS" != "" ] ; then
    log "The following pools are now of type $DEST_TYPE: $UPDATED_POOLS"
fi

log "Update successful"

exit 0
