#!/bin/bash
#
# Copyright (c) 2016-2017 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#

# This script is used to change the OpenStack 'admin' user's password 
# on Secondary Titanium Cloud Regions

# This script logs to user.log

PASSWORD_INPUT=$1

function set_admin_password()
{
	local SET_PASSWD_CMD="keyring set CGCS admin"
/usr/bin/expect << EOD
	set loguser_save [ log_user ]
	log_user 0
	set timeout_save timeout
	set timeout 60
	spawn $SET_PASSWD_CMD
	expect {
		"Password*" {
			send "$PASSWORD_INPUT\r"
			expect eof
		}
		timeout {
			puts "ERROR: Timed out"
			exit 1
		}
	}
	set timeout $timeout_save
	log_user $loguser_save
EOD

	local PASSWORD=$(keyring get CGCS admin)

	if [ "${PASSWORD}" == "${PASSWORD_INPUT}" ]; then
		return 0
	fi
	return 1
}

function validate_exec_environment()
{
	local TS_CONF_FILE="/usr/bin/tsconfig"
	if [ -f "$TS_CONF_FILE" ]; then
		source $TS_CONF_FILE
	else
		echo "ERROR: Missing $TS_CONF_FILE."
		exit 1
	fi

	local CONFIG_DIR=$CONFIG_PATH

	# check if it is running on a secondary region
	if [ -f "$PLATFORM_CONF_FILE" ]; then
		source $PLATFORM_CONF_FILE
		if [ "$region_config" = "no" ]; then
			echo "ERROR: This command is only applicable to a Secondary Region."
			exit 1
		fi
	else
		echo "ERROR: Missing $PLATFORM_CONF_FILE."
		exit 1
	fi

	# check if it is running on the active controller
	if [ ! -d $CONFIG_DIR ]; then
		echo "ERROR: Command must be run from the active controller."
		exit 1
	fi
	return 0
}

function validate_input()
{
	if [ -z "$PASSWORD_INPUT" ]; then
		echo "ERROR: Missing password input."
		echo "USAGE: $0 <password>"
		exit 1
	fi
	
	# check for space in the password	
	if [[ "$PASSWORD_INPUT" =~ ( |\') ]]; then
		echo "ERROR: Space is not allowed in the password."
		exit 1
	fi

	echo ""
	read -p "This command will update this Secondary Region's internal copy of the OpenStack Admin Password.
Are you sure you want to proceed (y/n)? " -n 1 -r

	echo ""
	if [[ ! $REPLY =~ ^[Yy]$ ]]; then
		echo "cancelled"
		exit 1
	fi
}

validate_exec_environment
validate_input
logger -p info -t $0 "Updating OpenStack Admin Password locally"
set_admin_password
if [ $? -eq 0 ]; then
    echo "The OpenStack Admin Password has been updated on this Secondary Region."
    echo "Please swact the controllers to allow certain services to resync the Admin password."
else
    echo "ERROR: Failed to update the Admin Password."
    exit 1
fi
exit 0
