#!/usr/bin/python3
# -*- coding: utf-8 -*-

import argparse
import os
import sys
from lxcbuild.app import App
from lxcbuild.image import Image

parser = argparse.ArgumentParser(description='VM application builder and packager')
parser.add_argument('-f', '--force', action='store_true', help='Force rebuild already built package')
parser.add_argument('buildpath', help='Either specific "lxcfile" or "meta" file or a directory containing at least one')

if len(sys.argv) < 2:
    parser.print_usage()
    sys.exit(1)
args = parser.parse_args()

buildpath = os.path.realpath(args.buildpath)
if os.path.isfile(buildpath):
    basename = os.path.basename(buildpath)
    if basename == 'lxcfile' or basename.endswith('.lxcfile'):
        image = Image(buildpath)
        image.build_and_pack(args.force)
    elif basename == 'meta' or basename.endswith('.meta'):
        app = App(buildpath)
        app.pack()
    else:
        print('Unknown file {} given, expected "lxcfile" or "meta"'.format(buildpath))
        sys.exit(1)
else:
    valid_dir = False
    for entry in os.scandir(buildpath):
        if entry.is_file() and (entry.name == 'lxcfile' or entry.name.endswith('.lxcfile')):
            valid_dir = True
            image = Image(entry.path)
            image.build_and_pack(args.force)
    meta = os.path.join(buildpath, 'meta')
    if os.path.exists(meta):
        valid_dir = True
        app = App(meta)
        app.pack()
    if not valid_dir:
        print('Directory {} doesn\'t contain anything to build, skipping'.format(buildpath))