#! /usr/bin/python3
"""
Copyright (c) 2010-2012 Dominik Oepen and Frank Morgner

This file is part of OpenPACE.

OpenPACE 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.

OpenPACE 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
OpenPACE.  If not, see <http://www.gnu.org/licenses/>.

Additional permission under GNU GPL version 3 section 7

If you modify this Program, or any covered work, by linking or combining it
with OpenSSL (or a modified version of that library), containing
parts covered by the terms of OpenSSL's license, the licensors of
this Program grant you additional permission to convey the resulting work.
Corresponding Source for a non-source form of such a combination shall include
the source code for the parts of OpenSSL used as well as that of the
covered work.

If you modify this Program, or any covered work, by linking or combining it
with OpenSC (or a modified version of that library), containing
parts covered by the terms of OpenSC's license, the licensors of
this Program grant you additional permission to convey the resulting work. 
Corresponding Source for a non-source form of such a combination shall include
the source code for the parts of OpenSC used as well as that of the
covered work.
"""

import os
import sys
import platform
import shutil

try:
    from chat import CVC
except ImportError:
    print("Failed to load OpenPACE python bindings.")
    print("Make sure you have the bindings installed and have PYTHONPATH and LD_LIBRARY_PATH setup correctly.")
    sys.exit(1)

def hash_dir(dir):
    files = os.listdir(dir)
    os.chdir(dir)
    for file in files:
        try:
            cvc = CVC(open(file).read())
            if platform.system() == 'Windows':
                print "Copying " + file + " to " + cvc.get_chr()
                shutil.copyfile(file, cvc.get_chr())
            else:
                print "Linking " + cvc.get_chr() + " to " + file
                os.symlink(file, cvc.get_chr())
        except Exception:
            pass

if __name__ == "__main__":
    dir = "/etc/eac"

    if len(sys.argv) > 1:
        dirlist = sys.argv[1:]
    elif os.environ.has_key('CVC_CERT_DIR'):
        dirlist = os.environ['CVC_CERT_DIR'].split(':')
    else:
        dirlist = [dir]

    for d in dirlist:
        if os.path.isdir(d) and os.access(d, os.W_OK):
            hash_dir(d)
