#!/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
from scylla_util import *

if __name__ == '__main__':
    if not is_ec2():
        sys.exit(0)
    parser = argparse.ArgumentParser(description='Verify EC2 configuration is optimized.')
    parser.add_argument('--nic', default='eth0',
                        help='specify NIC')
    args = parser.parse_args()

    if not is_valid_nic(args.nic):
        print('NIC {} doesn\'t exist.'.format(args.nic))
        sys.exit(1)

    aws = aws_instance()
    instance_class = aws.instance_class()
    en = aws.get_en_interface_type()
    match = re.search(r'^driver: (\S+)$', out('ethtool -i {}'.format(args.nic)), flags=re.MULTILINE)
    driver = match.group(1)

    if not en:
        colorprint('{red}{instance_class} doesn\'t support enhanced networking!{nocolor}', instance_class=instance_class)
        print('''To enable enhanced networking, please use the instance type which supports it.
More documentation available at:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/enhanced-networking.html#enabling_enhanced_networking''')
        sys.exit(1)
    elif not aws.is_vpc_enabled(args.nic):
        colorprint('{red}VPC is not enabled!{nocolor}')
        print('To enable enhanced networking, please enable VPC.')
        sys.exit(1)
    elif driver != en:
        colorprint('{red}Enhanced networking is disabled!{nocolor}')
        print('''More documentation available at:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/enhanced-networking.html''')
        sys.exit(1)

    colorprint('{green}This EC2 instance is optimized for Scylla.{nocolor}')
