#!/usr/bin/env python

# (c) Copyright 2015-2016 Hewlett Packard Enterprise Development LP
# (c) Copyright 2017 SUSE LLC
#
# 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 base64
import os
import os.path
import imp
import sys

path = os.path.dirname(os.path.realpath(__file__))

ardanaencrypt = imp.load_source('ardanaencrypt', path + '/../../../ardanaencrypt.py')

encryption_class = 'openssl'

ardanaencrypt_class = getattr(ardanaencrypt, encryption_class)

def generate_key(num_bytes=32, oldKey=None):
    value = base64.urlsafe_b64encode(os.urandom(num_bytes))
    if(len(sys.argv) > 1):
      value = sys.argv[1]

    # Make sure input value is not encrypted already
    if (value.startswith(ardanaencrypt_class.prefix) or
        value.startswith(ardanaencrypt_class.legacy_prefix)):
      return value

    obj = ardanaencrypt_class()

    # More base64 encoding to avoid any new line or special chars
    result = obj.prefix + base64.urlsafe_b64encode(obj.encrypt(value))

    return result


if __name__ == '__main__':
    print generate_key()
