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

"""Check and fix /home fstab entry

"""

import os
import sys
from pyeole.process import system_out

fstab = '/etc/fstab'
fb = open(fstab, 'r').readlines()
home_options = ['usrquota', 'grpquota']


def add_fstab_options(mountpoint, options=None):
    """Add options to fstab entry
    """
    if options is None:
        raise ValueError(u"Missing options to add to fstab entry.")

    if not isinstance(options, list):
        new_options = set([options])
    else:
        new_options = set(options)

    for i in range(len(fb)):
        ligne = fb[i]
        if testligne(ligne, mountpoint):
            old_string_options = ligne.split()[3]
            old_options = set(old_string_options.split(','))
            added_options = new_options - old_options
            if len(added_options) == 0:
                return True
            if 'defaults' in old_options:
                # Put default in front
                updated_options = ['defaults']
                old_options.remove('defaults')
            else:
                updated_options = []
            updated_options.extend(sorted(list(old_options | new_options)))
            updated_string_options = ",".join(updated_options)
            fb[i] = ligne.replace(old_string_options, updated_string_options)
            message_string = "Option{0} {1} ajoutée{0} à '{2}'"
            if len(added_options) > 1:
                plural = 's'
            else:
                plural = ''
            print(message_string.format(plural,
                                        ",".join(new_options - old_options),
                                        mountpoint))
            ecrire()
            remount(mountpoint)
            start_quota()
            return True
    return False


def remount(mountpoint):
    os.system('/bin/mount -o remount %s' % mountpoint)


def start_quota():
    """
    Start quota service
    """
    os.system('service quota start')

def enable_quota():
    """
    Enable quota on call
    """
    os.system('quotacheck -augf')
    #le service ne doit pas être en erreur
    os.system('systemctl reset-failed quotaon.service 2>/dev/null')
    os.system('quotaon -aug')

def check_quota():
    """
    Check quota if they are disabled during "instance" time
    """
    cmd = ['quotaon', '-paug']
    eni = {"LC_ALL": "C", "LANG": 'C', "PATH": '/sbin'}
    code, out, err = system_out(cmd, env=eni)
    status = out.strip().split('\n')
    for elm in status:
        if  not elm.endswith('on'):
            return False
    return True

def testligne(line, mountpoint):
    """
    recherche du point de montage "motif"
    """
    if line.startswith('#'):
        return False
    try:
        items = line.split()
        return items[1] == mountpoint
    except:
        return False


def ecrire():
    """
    Write fstab file
    """
    fh = open(fstab, 'w')
    for i in fb:
        fh.write(i)
    fh.close()

def main():
    """
    Main program, call fstab modification and quota enable.
    """
    #seulement à l'instance
    if sys.argv[-1] != 'instance':
        sys.exit(0)

    if not add_fstab_options('/home', home_options):
        add_fstab_options('/', home_options)

    if not check_quota():
        enable_quota()


if __name__ == "__main__":
    main()
