#!/usr/bin/python

from optparse import OptionParser

import sys
import os.path
    
try:
    import apt_pkg
except ImportError:
    print "Error importing apt_pkg, is python-apt installed?"
    sys.exit(1)
    
actions = { "markauto" : 1,
            "unmarkauto": 0
          }

def show_automatic(filename):
    if not os.path.exists(STATE_FILE):
        return
    auto = set()
    tagfile = apt_pkg.ParseTagFile(open(STATE_FILE))
    while tagfile.Step():
        pkgname = tagfile.Section.get("Package")
        autoInst = tagfile.Section.get("Auto-Installed")
        if int(autoInst):
            auto.add(pkgname)
    print "\n".join(sorted(auto))
    

def mark_unmark_automatic(filename, action, pkgs):
    " mark or unmark automatic flag"
    # open the statefile
    if os.path.exists(STATE_FILE):
        try:
            tagfile = apt_pkg.ParseTagFile(open(STATE_FILE))
            outfile = open(STATE_FILE+".tmp","w")
        except IOError, msg:
            print "%s, are you root?" % (msg)
            sys.exit(1)
        while tagfile.Step():
            pkgname = tagfile.Section.get("Package")
            autoInst = tagfile.Section.get("Auto-Installed")
            if pkgname in pkgs:
                if options.verbose:
                    print "changing %s to %s" % (pkgname,action)
                newsec = apt_pkg.RewriteSection(tagfile.Section,
                                       [],
                                       [ ("Auto-Installed",str(action)) ])
                pkgs.remove(pkgname)
                outfile.write(newsec+"\n")
            else:
                outfile.write(str(tagfile.Section)+"\n")
        if action == 1:
            for pkgname in pkgs:
                if options.verbose:
                    print "changing %s to %s" % (pkgname,action)
                outfile.write("Package: %s\nAuto-Installed: %d\n\n" % (pkgname, action))
        # all done, rename the tmpfile
        os.chmod(outfile.name, 0644)
        os.rename(outfile.name, STATE_FILE)
        os.chmod(STATE_FILE, 0644)


if __name__ == "__main__":
    apt_pkg.init()

    # option parsing
    parser = OptionParser()
    parser.usage = "%prog [options] {markauto|unmarkauto} packages..."
    parser.add_option("-f", "--file", action="store", type="string",
                      dest="filename",
                      help="read/write a different file")
    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose", default=False,
                      help="print verbose status messages to stdout")
    (options, args) = parser.parse_args()

    # get the state-file
    if not options.filename:
        STATE_FILE = apt_pkg.Config.FindDir("Dir::State") + "extended_states"
    else:
        STATE_FILE=options.filename

    if args[0] == "showauto":
        show_automatic(STATE_FILE)
    else:
        # get pkgs to change
        if args[0] not in actions.keys():
            parser.error("first argument must be 'markauto', 'unmarkauto' or 'showauto'")
        pkgs = args[1:]
        action = actions[args[0]]
        mark_unmark_automatic(STATE_FILE, action, pkgs)