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

# Copyright (C) 2015  Xyne
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# (version 2) as published by the Free Software Foundation.
#
# This program 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 General Public License for more details.
#
# 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.

import argparse
import json
import re
import sys




################################### Globals ####################################

PKGBASE_STRING = 'pkgbase'
PKGNAME_STRING = 'pkgname'


LIST_PATTERNS = (
  '^.*depends$',
  '^source$',
  '^backup$',
  '^.*sums$'
)

LIST_REGEXES = list(re.compile(p) for p in LIST_PATTERNS)



################################## Functions ###################################

def insert_pkgbase(pkginfo, pkgbase):
  '''
  Insert items from the pkgbase not overrridden by the package.
  '''
  for bk, bv in pkgbase.items():
    if bk not in pkginfo:
      if isinstance(bv, list):
        pkginfo[bk] = bv.copy()
      else:
        pkginfo[bk] = bv
  return pkginfo




def read_srcinfo(path):
  '''
  Read a SRCINFO file.
  '''

  srcinfo = dict()
  obj = None

  with open(path, 'r') as f:
    for line in f:
      stripped_line = line.strip()

      if not stripped_line or stripped_line[0] == '#':
        continue

      k, v = stripped_line.split(' = ', 1)

      if line[0] == '\t':
        for regex in LIST_REGEXES:
          if regex.match(k):
            try:
              obj[k].append(v)
            except KeyError:
              obj[k] = [v]
            break
        else:
          obj[k] = v

      else:
        obj = dict()
        if k == PKGBASE_STRING:
          srcinfo[PKGBASE_STRING] = obj
        else:
          try:
            srcinfo[k][v] = obj
          except KeyError:
            srcinfo[k] = {v : obj}

  if not PKGBASE_STRING in srcinfo:
    srcinfo[PKGBASE_STRING] = dict()
  return srcinfo



def get_pkginfo(srcinfo, pkgname):
  try:
    pkginfo = srcinfo[PKGNAME_STRING][pkgname]
    return insert_pkgbase(pkginfo.copy(), srcinfo[PKGBASE_STRING])
  except KeyError:
    return None



argparser = argparse.ArgumentParser(description='Convert SRCINFO files to JSON.')
argparser.add_argument(
  'srcinfo', nargs='+'
)



def main(args=None):
  pargs = argparser.parse_args(args)
  json.dump(tuple(read_srcinfo(p) for p in pargs.srcinfo), sys.stdout, indent='  ', sort_keys=True)


if __name__ == '__main__':
  try:
    main()
  except KeyboardInterrupt:
    pass
