#!/usr/bin/env python
#
# Copyright (c) 2013, Centre National de la Recherche Scientifique
#
# 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 os
import sys

sys.path.append('/var/lib/stratuslab/python')

import shutil
import stratuslab.Util as Util
from stratuslab.CommandBase import CommandBaseUser
from stratuslab.ConfigHolder import ConfigHolder

# initialize console logging
import stratuslab.api.LogUtil as LogUtil

LogUtil.get_console_logger()


class MainProgram(CommandBaseUser):
    """
    Copy the reference configuration file into the correct locaton for
    user.
    """

    existingFileMsg = \
        'won\'t overwrite file (%s); use --force to overwrite'

    refConfigFile = 'stratuslab-user.cfg.ref'

    def __init__(self):
        self.args = None
        super(MainProgram, self).__init__()

    def parse(self):

        self.parser.usage = '''%prog [options]'''

        self.parser.description = '''
Copies the reference StratusLab client configuration file into the
correct location for the user.  Will not overwrite existing file
unless forced.
'''

        self.parser.add_option('--force', action='store_true',
                               dest='force', default=False,
                               help='force overwrite of existing file')

        self.options, self.args = self.parser.parse_args()

    def checkOptions(self):
        pass

    def _get_config_path(self):
        src = os.path.join(Util.modulePath, '..', '..', '..', 'conf', self.refConfigFile)
        if not os.path.exists(src):
            src = os.path.join(Util.modulePath, '..', '..', '..', '..', 'etc', 'stratuslab', self.refConfigFile)
        return src

    def _create_parent_dir(self, dst):
        d = os.path.dirname(dst)
        if not os.path.exists(d):
            try:
                os.makedirs(d)
            except:
                raise Exception('cannot create directory %s' % d)

    def _copy_config(self, src, dst):
        try:
            shutil.copy(src, dst)
        except:
            raise Exception('error copying %s to %s' % (src, dst))

    def doWork(self):
        configHolder = ConfigHolder(self.options.__dict__)

        src = self._get_config_path()
        dst = configHolder.configFile

        if os.path.exists(dst) and not configHolder.force:
            Util.printError(self.existingFileMsg % dst)
        else:
            try:
                self._create_parent_dir(dst)
                self._copy_config(src, dst)
                Util.printDetail('wrote configuration file: %s' % dst)
            except Exception as e:
                Util.printError(e)


if __name__ == '__main__':
    try:
        MainProgram()
    except KeyboardInterrupt:
        print '\n\nExecution interrupted by the user... goodbye!'
