#!/bin/bash
#
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# 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.

set -eu

SCRIPT_NAME=$(basename $0)
SCRIPT_HOME=$(dirname $0)

function show_options {
    echo "Usage: $SCRIPT_NAME [options]"
    echo
    echo "Ensure that a given user exists."
    echo
    echo "Options:"
    echo "      -h -- this help"
    echo "      -e -- email"
    echo "      -n -- name"
    echo "      -t -- tenant"
    echo "      -u -- usercode"
    echo
    exit $1
}

EMAIL=''
NAME=''
TENANT=''
USERCODE=''

TEMP=`getopt -o hu:e:n:t: -n $SCRIPT_NAME -- "$@"`
if [ $? != 0 ]; then
    echo "Terminating..." >&2;
    exit 1;
fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true ; do
    case "$1" in
        -h) show_options 0;;
        -e) EMAIL=$2; shift 2 ;;
        -n) NAME=$2; shift 2 ;;
        -t) TENANT=$2; shift 2 ;;
        -u) USERCODE=$2; shift 2 ;;
        --) shift ; break ;;
        *) echo "Error: unsupported option $1." ; exit 1 ;;
    esac
done

EXTRA_ARGS=${1:-''}

if [ -z "$EMAIL" -o -z "$NAME" -o -z "$TENANT" -o -z "$USERCODE" -o -n "$EXTRA_ARGS" ]; then
    show_options 1
fi

echo "Checking for user $USERCODE"
#TODO: fix after bug 1392035 in the keystone client library
USER_ID=$(openstack user list | awk '{print tolower($0)}' |grep " ${USERCODE,,} " |awk '{print$2}')
if [ -z "$USER_ID" ]; then
    PASSWORD=''
    if [ -e os-asserted-users ]; then
        PASSWORD=$(awk "\$1==\"$USERCODE\" { print \$2 }" < os-asserted-users)
    fi
    if [ -z "$PASSWORD" ]; then
        PASSWORD=$(os-make-password)
        echo "$USERCODE $PASSWORD" >> os-asserted-users
    fi
    USER_ID=$(openstack user create --pass "$PASSWORD"
        --email "$EMAIL" $USERCODE | awk '$2=="id" {print $4}')
fi
#TODO: fix after bug 1392035 in the keystone client library
TENANT_ID=$(openstack project list | awk '{print tolower($0)}' |grep " ${TENANT,,} " |awk '{print$2}')
if [ -z "$TENANT_ID" ]; then
    TENANT_ID=$(openstack project create $TENANT | awk '$2=="id" {print $4}')
fi
if [ "$TENANT" = "admin" ]; then
    ROLE="admin"
else
    ROLE="_member_"
fi
ROLE_ID=$(openstack role show $ROLE | awk '$2=="id" {print $4}')
if openstack user role list --project $TENANT_ID $USER_ID | grep "${ROLE_ID}.*${ROLE}.*${USER_ID}" ; then
    echo "User already has role '$ROLE'"
else
    openstack role add --project $TENANT_ID --user $USER_ID $ROLE_ID
fi
echo "User $USERCODE configured."
