#!/usr/bin/env python
# Copyright (C) 2014-2015 Jurriaan Bremer.
# This file is part of VMCloak - http://www.vmcloak.org/.
# See the file 'docs/LICENSE.txt' for copying permission.

import argparse
import logging
import os.path

from sqlalchemy.orm.session import make_transient

from vmcloak.repository import Session, Image, image_path
from vmcloak.vm import VirtualBox

logging.basicConfig(level=logging.INFO)
log = logging.getLogger("vmcloak-clone")

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("name", type=str, help="Name of the image to clone from.")
    parser.add_argument("outname", type=str, help="Name of the new image.")
    args = parser.parse_args()

    session = Session()

    image = session.query(Image).filter_by(name=args.name).first()
    if not image:
        log.error("Image not found: %s", args.name)
        exit(1)

    outpath = os.path.join(image_path, "%s.vdi" % args.outname)

    m = VirtualBox(None)
    m.clone_hd(image.path, outpath)

    # Retain all fields but update the mode, name & path.
    make_transient(image)
    image.id = None
    image.mode = "normal"
    image.name = args.outname
    image.path = outpath

    session.add(image)
    session.commit()

if __name__ == '__main__':
    main()
