#!/usr/bin/python3
#
# Copyright 2020 ScyllaDB
#
# 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
#
#     http://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.

import os
import shutil
import sys
import pathlib
import signal
import argparse
from subprocess import check_output
sys.path.append('/opt/scylladb/scripts')
from scylla_util import *

def copytree(src, dst, symlinks=False, ignore=None):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isdir(s):
            shutil.copytree(s, d, symlinks, ignore)
        else:
            shutil.copy2(s, d)

def get_pid(name):
    return int(check_output(["pidof","-s",name]))

if __name__ == '__main__':
    root_disk = os.environ.get('ROOT_DISK', "/mnt/raid-disks/disk0")
    scylladconf_mount = os.environ.get('SCYLLAD_CONF_MOUNT', '/mnt/scylla.d/')

    parser = argparse.ArgumentParser(description='Scylla setup for k8s')
    parser.add_argument('--all', dest='all', action='store_true',
                        help='Setup everything, it has the same effect as setting each parameter individually')
    parser.add_argument('--install-dependencies', dest='install_dependencies', action='store_true',
                        help='installs Scylla dependencies')
    parser.add_argument('--setup-disks', dest='setup_disks', action='store_true',
                        help='format disks')
    parser.add_argument('--setup-network', dest='setup_network', action='store_true',
                        help='setup network iface')
    parser.add_argument('--run-io', dest='run_io', action='store_true',
                        help='run io tuning')
    args = parser.parse_args()

    if not args.all and not args.install_dependencies and not args.setup_disks and not args.setup_network and not args.run_io:
        parser.print_help()
        os.exit(1)

    if args.all or args.install_dependencies:
        run('/opt/scylladb/scripts/scylla_setup --no-coredump-setup --no-sysconfig-setup --no-raid-setup --no-io-setup --no-bootparam-setup --no-ec2-check --no-cpuscaling-setup --no-kernel-check --no-verify-package --no-enable-service --no-selinux-setup --no-version-check --no-node-exporter')

    if args.all or args.setup_disks:
        # setup XFS mount
        run('/opt/scylladb/scylla-machine-image/scylla_create_devices --scylla-data-root {}'.format(root_disk))

    if args.all or args.setup_network:
        run('/opt/scylladb/scripts/perftune.py --nic eth0 --mode sq --tune net')

        # Notify irqbalance about config change
        os.kill(get_pid("irqbalance"), signal.SIGHUP)

    if args.all or args.run_io:
        run('/opt/scylladb/scripts/scylla_io_setup')

        copytree('/etc/scylla.d', scylladconf_mount)

    pathlib.Path('/etc/scylla/machine_image_configured').touch()

    print("Setup done!")

    # infinite sleep
    signal.pause()
