#!/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.
#

""" 
<description>

@file:   apply_snapshot.py
@author: Taizo ITO <taizo@karesansui-project.info>
@copyright:    

<comment-ja>
指定したゲストOSにディスクを追加する

 使用方法: apply_snapshot.py [オプション]

  オプション:
    --version             プログラムのバージョンを表示
    -h, --help            使用方法を表示
    -n NAME, --name=NAME  ドメイン名を指定
    -i ID, --id=ID        スナップショットのIDを指定
</comment-ja>
<comment-en>
Attach a new disk device to the domain.

 usage: apply_snapshot.py [options]

  options:
    --version             show program's version number and exit
    -h, --help            show this help message and exit
    -n NAME, --name=NAME  Domain name
    -i ID, --id=ID        Snapshot serial ID
</comment-en>
"""

import os
import sys
import logging
from optparse import OptionParser

from ksscommand import KssCommand, KssCommandException

import __cmd__

try:
    import karesansui
    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 ApplySnapshot(KssCommand):

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

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            conn.set_domain_name(opts.name)
            self.up_progress(10)
            ret = conn.apply_snapshot(opts.id)
            self.up_progress(40)
        finally:
            conn.close()

        if ret is False:
            raise KssCommandException('failed to apply snapshot. - dom=%s id=%s' % (opts.name, opts.id))

        self.logger.info('Apply snapshot. - dom=%s id=%s' % (opts.name,opts.id))
        print >>sys.stderr, 'Apply snapshot. - dom=%s id=%s' % (opts.name,opts.id)
        self.up_progress(10)

        return True

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