#!/usr/bin/bash
# version 20
PROJECT=$1  # Save the PowerVC Project name
USER=$2     # Save the PowerVC Admin user name
PASSWD=$3   # Save the PowerVC Admin user password
if [[ "$PROJECT" == "" ]]
then 
	echo Hint: ./meter Project Admin-User Password
	echo The project names are listed with: openstack project list 
	exit 42
fi
# Change these to your local costs
export CPUUNITCOST=12.50
export RAMUNITCOST=0.01
export DISKUNITCOST=0.50

# earliest timestamp as PowerVC did not support metering before June 2016 this is a good start time
export TIMESTAMP="2016-06-07T00:00:00"

# Function to get a PowerVC REST API toekn for subsequestly gettin gthe metering data
# The token by default is value for 3 hours so we only ask for a new one every 2 hours
get_fresh_token() {
cat >out.auth.json <<EOF
{"auth": 
    {"scope": {"project": {"name": "$PROJECT", "domain": {"name": "Default"} } }, 
     "identity": {"methods": ["password"], "password": {"user": {"domain": {"name": "Default"}, "name": "$USER", "password": "$PASSWD" } } }
    }
}
EOF

# curl to Keystone security to logon and get the access token for later stats access.
curl -s -k -1 -i -X POST https://localhost:5000/v3/auth/tokens \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d @out.auth.json 1>token 
}

# Remind the user of the details we are fetching, the project and user name and cost numbers used
echo Metering for project:$PROJECT and user:$USER 
echo Costs: $CPUUNITCOST per CPU per day \(CPU Entitlement\)
echo Costs: $RAMUNITCOST per MB of memory per day
echo Costs: $DISKUNITCOST per GB of disk space per day

# We need the Project Id from the Project name supplied so look it up
PROJECTID=`openstack project list -f value | grep " "$PROJECT"$" | awk '{ printf "%s", $1 }' `
if [[ "$PROJECTID" == "" ]]
then 
	echo Project not found.  PROJECT = $PROJECT has PROJECTID = $PROJECTID
	exit 44
fi

# check if we have a token file called token and it is not too old
if [ ! -f token ]
then 
	#echo no token file = requesting one
	get_fresh_token
else
	if test `find "token" -mmin +120`
	then
	    #echo token is older than +120 minutes  = requesting new one
	    rm token
	    get_fresh_token
	#else
	    #echo token is not older than +120 minutes = reuse
	fi
fi

TOKEN=`grep ^X-Subject-Token token | awk '{ print $2 }' `
if [[ "$TOKEN" == "" ]]
then
echo No security token found for this user and password combination in the token file
exit 43
fi
# Debug echo Authorisation Token is $TOKEN

# everything ready TOKEN and PROJECTID
# get the metering / billing information from Ceilometer once each for CPU, memory and disk space
# note 86400 is the seconds in a day
# note http://localhost:8777/ could be replaced with the full https://localhost/powervc/openstack/metering/

curl -s -1 -k -H "X-Auth-Token:$TOKEN" \
-X GET "http://localhost:8777/v2/meters/total_vcpu/statistics?q.field=timestamp&q.op=gt&q.value=$TIMESTAMP&aggregate.func=max&period=86400&q.field=project_id&q.value=$PROJECTID" 1>out.vcpu

curl -s -1 -k -H "X-Auth-Token:$TOKEN" \
-X GET "http://localhost:8777/v2/meters/total_memory/statistics?q.field=timestamp&q.op=gt&q.value=$TIMESTAMP&aggregate.func=max&period=86400&q.field=project_id&q.value=$PROJECTID" 1>out.memory

curl -s -1 -k -H "X-Auth-Token:$TOKEN" \
-X GET "http://localhost:8777/v2/meters/total_volumes/statistics?q.field=timestamp&q.op=gt&q.value=$TIMESTAMP&aggregate.func=max&period=86400&q.field=project_id&q.value=$PROJECTID" 1>out.volumes


# output the spreadsheet comma separated values format heading information - 1st line creates the file then the rest append to it
echo Project,$PROJECT >$PROJECT.$USER.bill.csv
echo User,$USER >>$PROJECT.$USER.bill.csv
echo Date,`date` >>$PROJECT.$USER.bill.csv
echo  >>$PROJECT.$USER.bill.csv
echo CPU Costs,$CPUUNITCOST, per CPU per day \(CPU Entitlement\) >>$PROJECT.$USER.bill.csv
echo Memory Costs,$RAMUNITCOST, per MB of memory per day >>$PROJECT.$USER.bill.csv
echo Disk Costs,$DISKUNITCOST, per GB of disk space per day >>$PROJECT.$USER.bill.csv

# next process the ghastly json format for vcpu, memory and volumes
echo "\nVCPU Costs (actually Entitled Capacity)" >>$PROJECT.$USER.bill.csv
cat out.vcpu | grep "^\[" | sed 's/, {\"/\n/g' | sed 's/"//g' | sed 's/://g' | sed 's/,//g'  | \
awk 'BEGIN { printf "Date,vCPU,UnitPrice,Price\n" } { printf "%s,%.2f,%.2f,%.2f\n", $12, $4, COST, $4 * COST }' COST=$CPUUNITCOST | sed -e 's/T000000//' >>$PROJECT.$USER.bill.csv

echo "\nRAM Costs in Megabytes" >>$PROJECT.$USER.bill.csv
cat out.memory | grep "^\[" | sed 's/, {\"/\n/g' | sed 's/"//g' | sed 's/://g' | sed 's/,//g'  | \
awk 'BEGIN { printf "Date,MB,UnitPrice,Price\n" } { printf "%s,%.2f,%.2f,%.2f\n", $12, $4, COST, $4 * COST }' COST=$RAMUNITCOST | sed -e 's/T000000//' >>$PROJECT.$USER.bill.csv

echo "\nDISK Costs in Gigabytes" >>$PROJECT.$USER.bill.csv
cat out.volumes | grep "^\[" | sed 's/, {\"/\n/g' | sed 's/"//g' | sed 's/://g' | sed 's/,//g'  | \
awk 'BEGIN { printf "Date,GB,UnitPrice,Price\n" } { printf "%s,%.2f,%.2f,%.2f\n", $12, $4, COST, $4 * COST }' COST=$DISKUNITCOST | sed -e 's/T000000//' >>$PROJECT.$USER.bill.csv

echo "\nEnd of file" >>$PROJECT.$USER.bill.csv

# comment out the rm for debugging
rm out.*
echo Metering and Billing for project:$PROJECT and user:$USER output-file:$PROJECT.$USER.bill.csv
