#!/usr/bin/env python2
# -*- mode: python -*-
# -*- coding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2014 Lorenzo Villani
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#

from __future__ import print_function

import argparse
import collections
import hashlib
import json
import os
import os.path
import sys

from vagrant_metadata import *


def main():
    args = parse_args()

    if os.path.isfile("metadata.json"):
        with open("metadata.json", "r") as f:
            metadata = json.load(f)
    else:
        # Seed the metadata.json file if missing
        check_arg("baseurl", args)
        check_arg("description", args)
        check_arg("name", args)

        metadata = collections.OrderedDict([
            ("name", args.name),
            ("description", args.description),
            ("baseurl", args.baseurl),
            ("versions", []),
        ])

    with open("metadata.json", "w") as f:
        json.dump(process_directory(".", metadata, args.force), f, indent=4)


def parse_args():
    args_parser = argparse.ArgumentParser()
    args_parser.add_argument("-d", "--description", type=str)
    args_parser.add_argument("-f", "--force", action="store_true")
    args_parser.add_argument("-n", "--name", type=str)
    args_parser.add_argument("-u", "--baseurl", type=str)

    return args_parser.parse_args()


def check_arg(arg_name, args):
    if not getattr(args, arg_name, None):
        die("Please specify --%s on the command line" % arg_name)


def die(message):
    print(message)
    print("Aborting.")

    sys.exit(1)


if __name__ == "__main__":
    main()
