#!/usr/bin/env python3
# A Ravello SDK example for getting an application ID
#
# Copyright 2011-2016 Ravello Systems, Inc.
#
# 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.

import ravello_sdk
import sys
import os
import base64
import getpass
from argparse import ArgumentParser
from ravello_sdk import *

def usage():
	print("get-app-id.py <application-name>")
  
def get_credentials():
        with open(os.path.expanduser("~/.ravello_login"),"r") as pf:
                username = pf.readline().strip()
                encrypted_password = pf.readline().strip()
        password = base64.b64decode(encrypted_password).decode()
        return username,password

def get_user_credentials(username):

	password = None

	if username:
		password = getpass.getpass('Enter a Password: ')
	else:
		#read user credentials from .ravello_login file in user HOMEDIR
		username,password = get_credentials()

	if not username or not password:
		print('Error: User credentials are not set')
		return None,None

	return username,password

def mkparser():
	parser = ArgumentParser()
	parser.add_argument("-i", dest="id",default=0,type=int,help='application ID')
	parser.add_argument("-u", dest="username",default=None,help='Ravello user account name')
	parser.add_argument("app_name",default=None,help='application name')
	return parser

def connect(username, password):
	client = RavelloClient()
	try:
		client.login(username, password)
	except Exception as e:
		sys.stderr.write('Error: {!s}\n'.format(e))
		print('Error: Invalid user credentials, username {0}'.format(username))
		return None
	return client
 
def get_app_id(app_name,client):
	app_id = None
	for app in client.get_applications():
		if app['name'].lower() == app_name.lower():
			app_id = app['id']
	return app_id

def main():
	parser = mkparser()
	args = parser.parse_args()

	#Get user credentials
	username, password  = get_user_credentials(args.username)
	if not username or not password:
		exit(1)

	#Connect to Ravello
	client = connect(username, password)
	if not client:
		exit (1)

	app_id = get_app_id(args.app_name,client)

	if app_id:
		print(app_id)
	else:
		print("Error: Application {} not found".format(args.app_name))

if __name__ == '__main__':
    try:
       main()
    except Exception as e:
       sys.stderr.write('Error: {!s}\n'.format(e))

