#!/usr/libexec/platform-python
#  -*- coding: utf-8 -*-
# *****************************************************************************
# MLZ library of Tango servers
# Copyright (c) 2015-2020 by the authors, see LICENSE
#
# 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 2 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, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Module authors:
#   Alexander Lenz <alexander.lenz@frm2.tum.de>
#
# *****************************************************************************

import fnmatch
import os
import sys
from os import path

from entangle.server import get_global_config


def main():
    normal_dir = sys.argv[1]

    global_config = get_global_config()
    resdir = global_config[0]
    servitems = global_config[9]
    entangle_unit = '/lib/systemd/system/entangle@.service'
    wants_dir = normal_dir + '/entangle.target.wants'

    all_servers = [base for (base, ext) in
                   map(path.splitext, os.listdir(resdir)) if ext == '.res']
    all_servers.sort()

    fqdn = 'localhost'
    auto_servers = set()
    for (pattern, value) in servitems:
        if fnmatch.fnmatch(fqdn, pattern):
            for serv in value.split(','):
                auto_servers.update(fnmatch.filter(all_servers, serv.strip()))

    for srv in all_servers:
        symlink = '%s/entangle@%s.service' % (normal_dir, srv)
        os.symlink(entangle_unit, symlink)
        if srv in auto_servers:
            if not path.isdir(wants_dir):
                os.mkdir(wants_dir)
            os.symlink(symlink, '%s/%s' % (wants_dir, path.basename(symlink)))

    # the stamp file signals successful run of the generator
    open(normal_dir + '/entangle.stamp', 'w').close()


if __name__ == '__main__':
    try:
        main()
    except Exception:
        pass  # don't signal an error here
