#!/usr/bin/env python3
# package-tracker - Compare and track package versions in debian repositories
# Copyright (C) 2017 Andreas Kreuzer <andreas.kreuzer@open-infrastructure.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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, see <http://www.gnu.org/licenses/>.

import apt_pkg
import sys, os
import os.path
import apt
import apt.package
import aptsources
import aptsources.sourceslist
import getopt

read_sources = ''
compare_sources = ''
software = u'package-tracker'
program = sys.argv[0]

#FIXME use argparse instead getopt

def usage():
    print( 'Usage:', program, '-r <readsources> -c <comparesources>' )

try:
    command = sys.argv[1]
except IndexError:
    usage()
    sys.exit(2)

def readopts(argv):
    global read_sources, compare_sources
    try:
        opts, args = getopt.getopt(argv,"hr:c:",["read-sources=","compare-sources="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            usage()
            sys.exit(0)
        elif opt in ("-r", "--read-sources"):
            read_sources = arg
        elif opt in ("-c", "--compare-sources"):
            compare_sources = arg
    if not os.path.isfile(os.path.join("/etc/package-tracker", read_sources)):
        print( "File", read_sources, 'does not exist')
        usage()
        sys.exit(1)
    if not os.path.isfile(os.path.join("/etc/package-tracker", compare_sources)):
        print( "File", compare_sources, 'does not exist')
        usage()
        sys.exit(1)

if __name__ == "__main__":
    readopts(sys.argv[1:])

# -------------------------------------------
#
#  Function definitions

def config_apt(sources_file):
    apt_pkg.init_config()
    apt_pkg.config.set("Dir::State", "var/lib/" + software)
    apt_pkg.config.set("Dir::Cache", "var/cache/" + software)
    apt_pkg.config.set("Dir::Etc", "etc/" + software)
    apt_pkg.config.set("Dir::Etc::sourcelist", sources_file)
    apt_pkg.config.set("Dir::Log", "var/log/" + software)
    apt_pkg.init_system()

# -------------------------------------------
#
#  Initializing apt environment for
#  a list of packages wich will be compared
#  to a second sourcefile.
#

config_apt(read_sources)

acquire = apt_pkg.Acquire()
slist = apt_pkg.SourceList()

slist.read_main_list()
slist.get_indexes(acquire, True)

print( "Repositories to search packages from:" )
for src in slist.list:
    print( "\turi: ", src.uri, ' dist: ', src.dist )
print()

fromcache = apt_pkg.Cache()
print()
print(fromcache)
print('Size:', len(fromcache))

# -------------------------------------------
#
#  Initializing apt environment to compare
#  the prepared list of packages.
#

config_apt(compare_sources)

acquire2 = apt_pkg.Acquire()
slist2 = apt_pkg.SourceList()

slist2.read_main_list()
slist2.get_indexes(acquire2, True)

print( "Repositories to compare against:")
for src in slist2.list:
    print( "\turi: ", src.uri, ' dist: ', src.dist )

print()

tocache = apt_pkg.Cache()
print()
print(tocache)
print('Size:', len(tocache))
sys.exit(0)

for frompackage in fromcache.packages:
    print( frompackage.name )
    for version in frompackage.version_list:
        print( '  from: ', version.ver_str )
        for plist, _ in version.file_list:
            print( '    Origin: ', plist.origin, ' Component: ', plist.component, ' Archive: ', plist.archive)

    try:
        topackage = tocache[frompackage.name]
        for version in topackage.version_list:
            print( '  to: ', version.ver_str )
            for plist, _ in version.file_list:
                print( '    Origin: ', plist.origin, ' Component: ', plist.component, ' Archive: ', plist.archive)
    except KeyError:
        continue

sys.exit(0)
