#! @PYTHON@
"""
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/>.
"""

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 = "@sysconfdir@/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)
