#! /usr/bin/python3
# ------------------------------------------------------------------
#
#    Copyright (C) 2013 Canonical Ltd.
#
#    This program is free software; you can redistribute it and/or
#    modify it under the terms of version 2 of the GNU General Public
#    License published by the Free Software Foundation.
#
# ------------------------------------------------------------------

# FIXME: apparmor package from apparmor-utils is not a namespace package
import apparmor
from apparmor import click
import json
import optparse
import os
import sys

# where easyprof generated profiles are stored
apparmor_profiles = '/var/lib/apparmor/profiles'
# where apparmor caches its profiles (FIXME: adjust initscript)
apparmor_cache = '/var/cache/apparmor'
# where the apparmor click hook registers its click entries to be stored
apparmor_clicks = '/var/lib/apparmor/clicks'

def generate_profiles(clicks):
    files = []
    for missing in clicks:
        click_manifest = click.ClickManifest(os.path.join(apparmor_clicks, missing))
        easyprof_manifest = apparmor.click.transform(click_manifest)
        files.extend(click.to_profiles(easyprof_manifest, apparmor_profiles))
    return files

def main():
    parser = optparse.OptionParser()
    parser.add_option("-f", "--force", "--force-regenerate",
                      dest='force',
                      help='force regeneration of all click profiles',
                      action='store_true',
                      default=False)
    parser.add_option("-d", "--debug",
                      dest='debug',
                      help='emit debugging information',
                      action='store_true',
                      default=False)
    (opt, args) = parser.parse_args()

    if not len(args) == 0:
        error(usage())

    if not os.path.exists(apparmor_profiles):
        # FIXME log this
        os.makedirs(apparmor_profiles)

    if not os.path.exists(apparmor_cache):
        # FIXME log this
        os.makedirs(apparmor_cache)

    #try:
    if opt.force:
        missing_profiles = os.listdir(apparmor_clicks)
    else:
        missing_profiles = click.get_missing_profiles(apparmor_clicks, apparmor_profiles)
    missing_clicks = click.get_missing_clickhooks(apparmor_clicks, apparmor_profiles)

    load_profiles = generate_profiles(missing_profiles)
    click.load_profiles(load_profiles, args=['-r', '--write-cache', '--cache-loc=%s' %(apparmor_cache)])

    click.unload_profiles(missing_clicks)
    for m in missing_clicks:
        os.remove(os.path.join(apparmor_profiles, m))
    #except:
    #    print("something bad happened")

    return 0

if __name__ == "__main__":
    sys.exit(main())
