#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2018 ScyllaDB
#

#
# This file is part of Scylla.
#
# Scylla is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Scylla 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 Scylla.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys
import argparse
import re
import distro
import shutil

from scylla_util import *
from subprocess import run

if __name__ == '__main__':
    if os.getuid() > 0:
        print('Requires root permission.')
        sys.exit(1)

    parser = argparse.ArgumentParser(description='Optimize NTP client setting for Scylla.')
    parser.add_argument('--subdomain',
                        help='specify subdomain of pool.ntp.org (ex: centos, fedora or amazon)')
    args = parser.parse_args()

    if shutil.which('ntpd'):
        pkg_uninstall('ntp')
    if not shutil.which('chronyd'):
        pkg_install('chrony')
    if is_debian_variant():
        confpath = '/etc/chrony/chrony.conf'
        chronyd = 'chrony.service'
    else:
        confpath = '/etc/chrony.conf'
        chronyd = 'chronyd.service'
    with open(confpath) as f:
        conf = f.read()
    if args.subdomain:
        conf2 = re.sub(r'pool\s+([0-9]+)\.(\S+)\.pool\.ntp\.org', 'pool \\1.{}.pool.ntp.org'.format(args.subdomain), conf, flags=re.MULTILINE)
        with open(confpath, 'w') as f:
            f.write(conf2)
        conf = conf2
    chronyd = systemd_unit(chronyd)
    chronyd.enable()
    chronyd.restart()
    run('chronyc -a makestep', shell=True, check=True)
