#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function

import sys, os
from glob import glob
import subprocess
import opkg

if len(sys.argv) != 3:
	sys.stderr.write("Usage: opkg-compare-indexes <package_directory1> <package_directory2>\n")
	sys.exit(1)

pkg_dir1 = sys.argv[1]
pkg_dir2 = sys.argv[2]

pkgs1 = opkg.Packages()
pkgs1.read_packages_file(pkg_dir1 + '/Packages')

pkgs2 = opkg.Packages()
pkgs2.read_packages_file(pkg_dir2 + '/Packages')

names1 = list(pkgs1.packages.keys())
names2 = list(pkgs2.packages.keys())

## union of the two names lists
pkgs = {}
for name in names1:
    pkgs[name] = pkgs1.packages[name]
for name in names2:
    pkgs[name] = pkgs2.packages[name]

names = list(pkgs.keys())
names.sort() 
for name in names:
    pkg1 = None
    pkg2 = None
    if name in pkgs1.packages:
        pkg1 = pkgs1.packages[name]
    if name in pkgs2.packages:
        pkg2 = pkgs2.packages[name]
    if pkg1 and pkg2 and pkg1.version != pkg2.version:
        print("CHANGED: %s from version %s to %s (%s)" % (pkg1.package, pkg1.version, pkg2.version, pkg2.maintainer))
        cmd = "opkg-diff %s %s > %s " % ((pkg_dir1 + pkg1.filename),  (pkg_dir2 + pkg2.filename), (pkg1.package + '.diff'))
        print(cmd)
        subprocess.call(cmd)
    if not pkg1:
        print("NEW: %s version %s (%s)"% (pkg2.package, pkg2.version, pkg2.maintainer))
    if not pkg2:
        print("DELETE: %s version %s (%s)"% (pkg1.package, pkg1.version, pkg1.maintainer))
    
