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

# Copyright 2021 Mir Calculate. http://www.calculate-linux.org
#
#  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 argparse
import sys
import os
import re

class ArgumentParserCheckDomainFastlogin(argparse.ArgumentParser):
    def __init__(self):
        super(ArgumentParserCheckDomainFastlogin, self).__init__(
            description="Check domain user for fastlogin")
        self.add_argument('--user', required=True,
                           help='full variable name')

def read_file(filename):
    try:
        if os.path.exists(filename):
            with open(filename, 'r') as f:
                return f.read()
    except (OSError, IOError) as e:
        pass
    return ""

def get_git_fetchhead(gitpath):
    headpath = os.path.join(gitpath, "FETCH_HEAD")
    return read_file(headpath)

def get_git_head_commit(gitpath):
    headpath = os.path.join(gitpath, "HEAD")
    head = read_file(headpath)
    m = re.search("^ref: (refs/heads/.*)$", head, re.M)
    if m:
        commitfile = os.path.join(gitpath, m.group(1))
        return read_file(commitfile)
    return ""

def get_git_data(gitpath):
    data = get_git_fetchhead(gitpath)
    if not data:
        data = get_git_head_commit(gitpath)
    return data

def get_calculate_env_data(envfile):
    return read_file(envfile)

def get_ini_env_data(envfile):
    return read_file(envfile)

def get_emergelog_data(logdata):
    return read_file(logdata)[-200:]

def get_fast_login_resources(fastlogin_path):
    return [x.strip() for x in read_file(fastlogin_path).split("\n") if x]

def get_xorg_log_resolution():
    xlog = "/var/log/Xorg.0.log"
    try:
        if os.access(xlog, os.R_OK):
            with open(xlog, 'r') as f:
                logdata = f.read()
            for re_pat in (
                "Output [\S]+ using initial mode (\d+)x(\d+)",
                "Virtual screen size determined to be"
                " ([0-9]+)\s*x\s*([0-9]+)",
                'Setting mode "(\d+)x(\d+)[0-9@]"',
                "Virtual size is (\d+)x(\d+)"):
                reXorgLogParser = re.compile(re_pat, re.S)
                resXorgLogParser = reXorgLogParser.search(logdata)
                if resXorgLogParser:
                    return "%sx%s" % resXorgLogParser.groups()
    except Exception:
        pass
    return "1024x768"

def check_domain_fastlogin(username):
    import hashlib
    user_fastlogin = "/home/{}/.calculate/fastlogin-domain".format(username)
    user_fastlogin_dn = "/home/{}/.calculate".format(username)
    fastlogin_path = "/var/lib/calculate/calculate-desktop/fastlogin-domain"
    if not os.path.exists(fastlogin_path):
        return False
    old_hash = read_file(user_fastlogin).strip()
    m = hashlib.md5()
    for res in get_fast_login_resources(fastlogin_path):
        if res.endswith(".git"):
            data = get_git_data(res)
        elif res.endswith("emerge.log"):
            data = get_emergelog_data(res)
        elif res.endswith("calculate.env"):
            data = get_calculate_env_data(res)
        elif res.endswith("ini.env"):
            data = get_ini_env_data(res)
        else:
            data = get_general_data(res)
        m.update(data.encode())
    m.update(get_xorg_log_resolution().encode())
    new_hash = m.hexdigest()
    if old_hash != new_hash:    
        if os.path.exists(user_fastlogin_dn):
            with open(user_fastlogin,'w') as f:
                f.write("%s\n"%new_hash)
        return False
    return True

if __name__ == '__main__':
    ap = ArgumentParserCheckDomainFastlogin()
    args = ap.parse_args()
    if check_domain_fastlogin(args.user):
        sys.exit(0)
    else:
        sys.exit(1)
