#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009 HDE, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#

import os
import sys
import time
import logging
from optparse import OptionParser

from ksscommand import KssCommand, KssCommandException, KssCommandOptException

import __cmd__

try:
    import karesansui
    from karesansui.lib.const import VIRT_SNAPSHOT_DIR 
    from karesansui import __version__
    from karesansui.lib.virt.virt import KaresansuiVirtConnection
    from karesansui.lib.utils import load_locale
except ImportError:
    print >>sys.stderr, "[Error] karesansui package was not found."
    sys.exit(1)

_ = load_locale()

usage = '%prog [options]'

def getopts():
    optp = OptionParser(usage=usage, version=__version__)
    optp.add_option('-n', '--name', dest='name', help=_('Domain name'))
    optp.add_option('-i', '--id', dest='id', help=_('Snapshot serial ID'))
    return optp.parse_args()

def chkopts(opts):
    if not opts.name:
        raise KssCommandOptException('ERROR: -n or --name option is required.')
    #if not opts.id:
    #    raise KssCommandOptException('ERROR: -i or --id option is required.')

class TakeSnapshot(KssCommand):

    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        if not opts.id:
            opts.id = "%f" % time.time()

        target_filepath = "%s/%s/%s" % (VIRT_SNAPSHOT_DIR, opts.name, opts.id)
        conn = KaresansuiVirtConnection(readonly=False)
        try:
            #conn.set_domain_name(opts.name)
            if not os.path.exists(target_filepath):
                try:
                    self.up_progress(10)
                    conn.take_snapshot(opts.name, opts.id)
                    self.up_progress(50)
                    self.logger.info('Has successfully created the snapshot. - path=%s' % target_filepath)
                except:
                    self.logger.error('Failed to take a snapshot. - path=%s' % target_filepath)
                    print >>sys.stderr, 'Failed to take a snapshot. - path=%s : detail %s' \
                          % (target_filepath, ''.join(e.args))
                    raise

                if os.path.isfile(target_filepath) is False:
                    raise KssCommandException('Took a snapshot. - path=%s' % target_filepath)

            else:
                raise KssCommandException('snapshot already exists. - %s' % target_filepath)
            
            return True
        finally:
            conn.close()

if __name__ == "__main__":
    target = TakeSnapshot()
    sys.exit(target.run())
