#!/usr/bin/env python3

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Wrapper around znc.

znc needs its config file to be writable
(https://github.com/znc/znc/issues/975), so this provides a temporary writable
copy. This also merges the data and config directories into the single tree that
znc needs.
"""

import json
import pathlib
import shutil
import subprocess
import sys
import tempfile

# {% from 'irc/bouncer/map.jinja' import irc_bouncer %}
_CONFIG_DIR = pathlib.Path('/etc/znc')
_DATA_DIR = pathlib.Path('/var/lib/znc')
_MUTABLE = json.loads('{{ irc_bouncer.znc_mutable | tojson }}')


def main():
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = pathlib.Path(temp_dir)
        shutil.copytree(_CONFIG_DIR, temp_path, dirs_exist_ok=True)
        for mutable_path in _MUTABLE['global_dirs'] + _MUTABLE['global_files']:
            temp_path.joinpath(mutable_path).parent.mkdir(parents=True,
                                                          exist_ok=True)
            temp_path.joinpath(mutable_path).symlink_to(
                _DATA_DIR.joinpath(mutable_path))
        return subprocess.run((
            'znc',
            f'--datadir={temp_dir}',
            *sys.argv[1:],
        )).returncode


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