#!/usr/bin/python3.13 -tt
#
# Queries and manages VM installation jobs, started by vm-install
#
# Copyright 2007 Novell, Inc.
# Author: Charles Coffing <ccoffing@novell.com>
#
# This software may be freely redistributed under the terms of the GNU
# general public license.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA 

from __future__ import print_function
import optparse
import sys

import vminstall
import vminstall.job

parser = optparse.OptionParser(description="""Queries and manages VM creation jobs.  Consult the man page for complete usage and examples.""")

parser.add_option('-l', '--list',   action='store_true', dest='list', help="list VM creation jobs")
parser.add_option('-c', '--cancel', type='string', dest='cancel', help="cancel a job and destroy the VM")
parser.add_option('-s', '--status', type='string', dest='status', help="print status of a job")
parser.add_option('-d', '--detach', type='string', dest='detach', help="delete job but keep VM")
parser.add_option('-D', '--delete', type='string', dest='delete', help="delete job and VM")

(options, args) = parser.parse_args()

r = 0
try:
    if options.cancel:
        vminstall.job.cancel(options.cancel)
    elif options.status:
        sys.stdout.write(vminstall.job.status(options.status))
    elif options.detach:
        vminstall.job.detach(options.detach)
    elif options.delete:
        vminstall.job.delete(options.delete)
    else:  # implicit or explicit "--list"
        for job in vminstall.job.list():
            print(job)
except KeyboardInterrupt:
    print('%s\n' % vminstall.msg.aborted, file=sys.stderr)
    r = 1
except vminstall.Error as e:
    print('%s: %s' % (vminstall.msg.error, str(e)), file=sys.stderr)
    r = e.exit_code()
except Exception as e:
    print('%s: %s' % (vminstall.msg.error, str(e)), file=sys.stderr)
    r = 1

sys.exit(r)
