#!/usr/bin/env python3

"""
This is a very primitive AUR package installer. It uses input files to specify
target packages and dependencies along with maintainers for each. If the
maintainers match those given then the package is trusted and installed.


The input files (called "aur chains") have the following format:

    <pkgname> <maintainer>
    <pkgname> <maintainer>
    <pkgname> <maintainer>
    ...

If <pkgname> is preceded by an asterisk (*) then it will be explicitly
installed.

Example input file for freecad:

    *freecad mickele
    eigen3 Kringel
    libspnav jaham
    opencascade gborzi
    pivy-hg eworm
    swig1 hilton
    soqt eworm
    coin eworm

"""

import AUR
import sys
import os.path



def get_chain(path):
  targets = set()
  queue = []
  with open(path) as f:
    for line in f:
      line = line.strip()
      if not line or line[0] == '#':
        continue
      name, maintainer = line.split(None, 1)
      if name[0] == '*':
        name = name[1:]
        targets.add(name)
      queue.append((name,maintainer))
  return targets, queue


def main(paths):
  for path in paths:
    targets, queue = get_chain(path)
    urls = []
    cmds = ""
    name = os.path.basename(path)
    build_file = name + '.build.sh'
    links_file = name + '.links'

    aur = AUR.AUR()
    # use single query to retreive info
    aur.info(p for p,m in queue)

    with open(build_file, 'w') as b:
      with open(links_file, 'w') as l:
        b.write('''#!/bin/bash
set -e
aria2c -c -i {links_file}

'''.format(links_file=links_file))

        for pkg, maintainer in reversed(queue):
          info = aur.info(pkg)[0]
          if info['Maintainer'] == maintainer:
            l.write('https://aur.archlinux.org' + info['URLPath'] + '\n')
            b.write("""bsdtar -xf '{archive}'
cd -- '{pkg}'
makepkg "$@"
cd -
""".format(archive=os.path.basename(info['URLPath']), pkg=pkg))
            if pkg not in targets:
              b.write("sudo pacman -D --asdeps '%s'\n" % pkg)
            b.write('\n')
          else:
            sys.stderr.write("error: unexpected maintainer for %s: %s\n" % (pkg, info['Maintainer']))
            sys.exit(1)

if __name__ == '__main__':
  main(sys.argv[1:])
