#!/usr/bin/python3
#
# 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 shutil
from scylla_util import *

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

    if not shutil.which('mkfs.xfs'):
        if is_debian_variant():
            run('apt-get install -y xfsprogs')
        elif is_gentoo_variant():
            run('emerge -uq sys-fs/xfsprogs')
        elif is_redhat_variant():
            run('yum install -y xfsprogs')

    makedirs('/var/tmp/mnt')
    run('dd if=/dev/zero of=/var/tmp/kernel-check.img bs=1M count=128', silent=True)
    run('mkfs.xfs /var/tmp/kernel-check.img', silent=True)
    run('mount /var/tmp/kernel-check.img /var/tmp/mnt -o loop', silent=True)
    ret = run('iotune --fs-check --evaluation-directory /var/tmp/mnt', exception=False)
    run('umount /var/tmp/mnt')
    shutil.rmtree('/var/tmp/mnt')
    os.remove('/var/tmp/kernel-check.img')
    if ret == 0:
        print('This is a supported kernel version.')
    else:
        if dist_name() == 'Ubuntu' and dist_ver() == '14.04':
            print('Please upgrade to a newer kernel version by executing \'apt-get install linux-image-generic-lts-vivid && reboot\'.')
        else:
            print('Please upgrade to a newer kernel version.')
            print(' see http://www.scylladb.com/kb/kb-fs-not-qualified-aio/ for details')
    sys.exit(ret)
