"""
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.

This program and the accompanying materials are made available under
the terms of the 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 os
import platform
import time

import tinctest

from gppylib.commands.base import Command
from tinctest.lib import run_shell_command

class GPFDISTError(Exception):
    pass

class GPFDIST:

    def __init__(self, port, hostname, directory=None):
        "init"
        self.port = port
        self.hostname = hostname
        self.secure = False
        self.ssl_cert = ""
        if directory is None:
            directory = os.getcwd()
        self.directory = directory
        self.gphome = os.environ.get("GPHOME")

        # Ensure we use compatible ps command on Solaris platform
        self.ps_command = 'ps'
        if platform.system() in ['SunOS']:
            self.ps_command = '/bin/ps'

    def gethost(self):
        return self.hostname

    def getport(self):
        return self.port

    def getdir(self):
        return self.directory

    def startGpfdist(self, options="", port=None, raise_assert=True, ssl=None):
        """
        start hosting the data
        @comment: Why do we need to ssh to a host that is localhost
                  killGpfdist does not support kill process on other host
        @note: If we are to use ssh subprocess, we will go to the home folder,
            let's revisit this with remote command so that it works for starting 
            gpfdist on remote host
        """
        if port is None:
            port = self.port
        else:
            port = str(port)
        if ssl is None:
            ssl = ""
        else:
            self.secure = True
            self.ssl_cert = ssl
            ssl = "--ssl %s" % self.ssl_cert

        directory = self.directory

        gpfdist_cmd = "gpfdist -p %s -d %s %s %s" % (port, directory, options, ssl)
        cmd = "gpssh -h %s 'source %s/greenplum_path.sh; %s > /dev/null &'" % (self.hostname, self.gphome, gpfdist_cmd)
        
        res = {'rc':0, 'stderr':'', 'stdout':''}
        run_shell_command(cmd, 'gpfdist', res)
        if res['rc'] > 0:
            raise Exception("Failed to start gpfdist on host %s and port %s with non-zero rc" %(self.hostname, port))