# Copyright 2013: Mirantis Inc.
# 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.

import ConfigParser
import json
import os
import pwd
import shutil
import subprocess
import tempfile


TEST_ENV = {
    "OS_USERNAME": "admin",
    "OS_PASSWORD": "admin",
    "OS_TENANT_NAME": "admin",
    "OS_AUTH_URL": "http://fake/",
}


class RallyCmdError(Exception):

    def __init__(self, code, output):
        self.code = code
        self.output = output

    def __str__(self):
        return "Code: %d Output: %s\n" % (self.code, self.output)

    def __unicode__(self):
        return "Code: %d Output: %s\n" % (self.code, self.output)


class TaskConfig(object):

    def __init__(self, config):
        config_file = tempfile.NamedTemporaryFile(delete=False)
        config_file.write(json.dumps(config))
        config_file.close()
        self.filename = config_file.name

    def __del__(self):
        os.unlink(self.filename)


class Rally(object):
    """Create and represent separate rally installation.

    Usage:

        rally = Rally()
        rally("deployment", "create", "--name", "Some Deployment Name")
        output = rally("deployment list")

    """

    def __init__(self, fake=False):
        # NOTE(sskripnick): we shoud change home dir to avoid races
        # and do not touch any user files in ~/.rally
        os.environ["HOME"] = pwd.getpwuid(os.getuid()).pw_dir
        subprocess.call("rally deployment config > /tmp/.rd.json", shell=True)
        self.tmp_dir = tempfile.mkdtemp()
        os.environ["HOME"] = self.tmp_dir
        config_filename = os.path.join(self.tmp_dir, "conf")
        config = ConfigParser.RawConfigParser()
        config.add_section("database")
        config.set("database", "connection", "sqlite:///%s/db" % self.tmp_dir)
        with open(config_filename, "wb") as conf:
            config.write(conf)
        self.args = ["rally", "--config-file", config_filename]
        subprocess.call(["rally-manage", "--config-file", config_filename,
                         "db", "recreate"])
        self("deployment create --file /tmp/.rd.json --name MAIN")

    def __del__(self):
        shutil.rmtree(self.tmp_dir)

    def __call__(self, cmd, getjson=False):
        if not isinstance(cmd, list):
            cmd = cmd.split(" ")
        try:
            output = subprocess.check_output(self.args + cmd,
                                             stderr=subprocess.STDOUT)
            if getjson:
                return json.loads(output)
            return output
        except subprocess.CalledProcessError as e:
            raise RallyCmdError(e.returncode, e.output)

@@ -627,28 +627,44 @@
 e.%0A%0A
+from six.moves 
 import 
-C
+c
 onfig
-P
+p
 arser%0A
+%0A
 impo
@@ -741,17 +741,16 @@
 mpfile%0A%0A
-%0A
 TEST_ENV
@@ -879,16 +879,79 @@
 e/%22,%0A%7D%0A%0A
+DEPLOYMENT_FILE = %22/tmp/rally_functests_main_deployment.json%22%0A%0A
 %0Aclass R
@@ -1421,16 +1421,32 @@
 (config)
+.encode(%22utf-8%22)
 )%0A      
@@ -2038,66 +2038,153 @@
     
-subprocess.call(%22rally deployment config %3E /tmp/.rd.json%22,
+if not os.path.exists(DEPLOYMENT_FILE):%0A            subprocess.call(%22rally deployment config %3E %25s%22 %25 DEPLOYMENT_FILE,%0A                           
  she
@@ -2272,24 +2272,73 @@
 elf.tmp_dir%0A
+%0A        if %22RCI_KEEP_DB%22 not in os.environ:%0A    
         conf
@@ -2390,24 +2390,28 @@
 f%22)%0A        
+    
 config = Con
@@ -2407,23 +2407,23 @@
 onfig = 
-C
+c
 onfig
-P
+p
 arser.Ra
@@ -2442,24 +2442,28 @@
 r()%0A        
+   
+ 
 config.add_s
@@ -2477,24 +2477,28 @@
 %22database%22)%0A
+    
         conf
@@ -2529,16 +2529,39 @@
 ection%22,
+%0A                      
  %22sqlite
@@ -2595,16 +2595,20 @@
         
+ 
+   
 with ope
@@ -2628,17 +2628,16 @@
 name, %22w
-b
 %22) as co
@@ -2648,24 +2648,28 @@
             
+ 
+   
 config.write
@@ -2679,24 +2679,28 @@
 nf)%0A        
+   
+ 
 self.args = 
@@ -2743,16 +2743,20 @@
 lename%5D%0A
+    
         
@@ -2847,16 +2847,20 @@
         
+ 
+   
 %22db%22, %22r
@@ -2882,65 +2882,185 @@
     
-self(%22deployment create --file /tmp/.rd.json --name MAIN%22
+else:%0A            self.args = %5B%22rally%22%5D%0A            subprocess.call(%5B%22rally-manage%22, %22db%22, %22recreate%22%5D)%0A%0A        self(%22deployment create --file %25s --name MAIN%22 %25 DEPLOYMENT_FILE
 )%0A%0A 
@@ -3470,16 +3470,32 @@
 n output
+.decode(%22utf-8%22)
 %0A       

Add option to keep db settings in functional tests