#!/usr/bin/env python3
#  -*- coding: utf-8 -*-
# *****************************************************************************
# Copyright (c) 2015-2019 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>
#   Enrico Faulhaber <enrico.faulhaber@frm2.tum.de>
#
# *****************************************************************************

import os
import sys
from os import path

from frappy.lib import generalConfig


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

    generalConfig.init()
    config_dir = generalConfig['confdir']

    frappy_unit = '/lib/systemd/system/frappy@.service'
    wants_dir = normal_dir + '/frappy.target.wants'

    all_servers = [base[:-4] if base.endswith('_cfg') else base for (base, ext) in
                   map(path.splitext, os.listdir(config_dir)) if ext == '.py']
    all_servers.sort()

    for srv in all_servers:
        symlink = '%s/frappy@%s.service' % (normal_dir, srv)
        os.symlink(frappy_unit, symlink)
        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 + '/frappy.stamp', 'w').close()


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