#!/usr/bin/python3
#   Copyright (C) 2013 Canonical Ltd.
#
#   Author: Scott Moser <scott.moser@canonical.com>
#
#   Simplestreams is free software: you can redistribute it and/or modify it
#   under the terms of the GNU Affero General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or (at your
#   option) any later version.
#
#   Simplestreams is distributed in the hope that it will be useful, but
#   WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
#   or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
#   License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with Simplestreams.  If not, see <http://www.gnu.org/licenses/>.

import argparse
import json
import os
import sys
from simplestreams import generate_simplestreams
from simplestreams import util

import toolutil


def tab2items(content):
    # tab content is
    #    content-id product_name version_name img_name [key=value [key=value]]
    # return a list with each item containing:
    #    (content_id, product_name, version_name, item_name, {data})
    items = []
    for line in content.splitlines():
        if line.startswith("#"):
            continue
        fields = line.split('\t')
        content_id, prodname, vername, itemname = fields[0:4]

        kvdata = {}
        if len(fields) > 4:
            for field in fields[4:]:
                key, value = field.split("=")
                if key == "size":
                    kvdata[key] = int(value)
                else:
                    kvdata[key] = value

        items.append((content_id, prodname, vername, itemname, kvdata,))

    return items


def main():
    parser = argparse.ArgumentParser(
        description="create content tree from tab data")

    parser.add_argument("input", metavar='file',
                        help=('source tab delimited data'))

    parser.add_argument("out_d", metavar='out_d',
                        help=('create content under output_dir'))

    parser.add_argument('--sign', action='store_true', default=False,
                        help='sign all generated files')

    args = parser.parse_args()

    if args.input == "-":
        tabinput = sys.stdin.read()
    else:
        with open(args.input, "r") as fp:
            tabinput = fp.read()

    streamdir = "streams/v1"

    items = tab2items(tabinput)
    updated = util.timestamp()
    data = {'updated': updated, 'datatype': 'image-downloads'}
    trees = generate_simplestreams.items2content_trees(items, data)
    out_filenames = generate_simplestreams.write_streams(args.out_d, trees,
                                                         updated)
    if args.sign:
        for outf in out_filenames:
            sys.stderr.write("signing %s\n" % filef)
            toolutil.signjson_file(filef)

    return

if __name__ == '__main__':
    sys.exit(main())

# vi: ts=4 expandtab
