#!/usr/bin/python3

# -*- coding: utf-8 -*-

# OpenCocon config parser
# ここでは、cnf_file から、有効な行のみを取得し、merged_config にある設定に追記・上書きして出力する。
# ファイルが指定されているオプションに対しては、ファイルを /tmp へコピーする。
# このスクリプトではパースのみを行う。各オプションに対する処理はおこなわない。

import sys
import os
import tempfile
import shutil
import configparser
import pathlib
import random

# _only_booting のつく設定：
#   X11が起動する前にしか読み込まない。[DEFAULT] セクションでしか書くことができない。
allow_option_bool=["COCON_WAIT_CONNECTED",
                   "COCON_POWEROFF_AFTER_AUTOCONNECT",
                   "COCON_SE_SET_GATEWAY_ONVPN",
                   "COCON_WAIT_CONNECTED",
                   "COCON_MUTE_MASTER_ON_BOOT",
                   "COCON_RDP_MODEM"]
allow_option_bool_only_booting=["COCON_FORCEFB",
                   "COCON_MUTE_MASTER_ON_BOOT"]
allow_option_str=["COCON_AUTOCONNECT",
                  "COCON_AUTOVPN",
                  "COCON_RDP_HOST",
                  "COCON_RDP_USER",
                  "COCON_RDP_DOMAIN",
                  "COCON_RDP_KBD",
                  "COCON_VNC_HOST",
                  "COCON_VNC_USER",
                  "COCON_SPICE_HOST",
                  "COCON_WWW_START",
                  "COCON_X_HOST",
                  "COCON_SE_HOST",
                  "COCON_SE_USER",
                  "COCON_SE_HUB",
                  "COCON_SE_AUTH_METHOD"]
allow_option_str_only_booting=["COCON_KBD_CONSOLE",
                  "COCON_KBD_X_MODEL",
                  "COCON_KBD_X_LAYOUT",
                  "COCON_KBD_X_VARIANT"]
allow_option_int=["COCON_RDP_RFX",
                  "COCON_SPICE_PORT",
                  "COCON_SPICE_TLSPORT"]
allow_option_int_only_booting=["COCON_MASTER_VOLUME"]
allow_option_file=["COCON_RDP_RDPFILE",
                   "COCON_SSH_KEYFILE"]
allow_option_file_only_booting=["COCON_XCONF_ADD"]

cnf_file_moveto="/tmp/.coconfiles.$RANDOM/"


# 有効なBooleanオプションであることを判定する
def detect_boolean_value(in_str):
    lower_str = in_str.lower()
    if (lower_str == 'true' or lower_str == 'on'
        or lower_str == '1' or lower_str == 'yes'):
        # print('=1')
        return '1'
    if (lower_str == 'false' or lower_str == 'off'
        or lower_str == '0' or lower_str == 'no'):
        # print('=0')
        return '0'
    return False

def pickup_bool_option(key, value, is_only_booting):
    #print(key.upper() + ', ' + value)
    for cur_key in allow_option_bool:
        if key == cur_key.lower():
            print('match: ' + cur_key)
            return detect_boolean_value(value)

    if is_only_booting == True:
        for cur_key in allow_option_bool_only_booting:
            if key == cur_key.lower():
                print('match: ' + cur_key)
                return detect_boolean_value(value)

    # Not found.
    return False


# 有効なStringオプションであることを判定する
def pickup_str_option(key, value, is_only_booting):
    #print(key.upper() + ', ' + value)
    for cur_key in allow_option_str:
        if key == cur_key.lower():
            print('match: ' + cur_key)
            # TODO : Escape Special Characters?
            return value

    if is_only_booting == True:
        for cur_key in allow_option_str_only_booting:
            if key == cur_key.lower():
                print('match: ' + cur_key)
                # TODO : Escape Special Characters? 
                return value

    # Not found.
    return False


# 有効なIntegerオプションであることを判定する
def pickup_int_option(key, value, is_only_booting):
    #print(key.upper() + ', ' + value)
    for cur_key in allow_option_int:
        if key == cur_key.lower():
            print('match: ' + cur_key)
            try:
                return int(value)
            except:
                return False

    if is_only_booting == True:
        for cur_key in allow_option_int_only_booting:
            if key == cur_key.lower():
                print('match: ' + cur_key)
                try:
                    return int(value)
                except:
                    return False

    # Not found.
    return False


# 有効なFileオプションであることを判定する
def pickup_file_option(key, value, is_only_booting, tmp_path):
    # print(key.upper() + ', ' + value)
    for cur_key in allow_option_file:
        if key == cur_key.lower():
            print('match: ' + cur_key)

            # Filter filename : exclude path string
            filename = pathlib.Path(value).name

            # Check file exists
            if pathlib.Path(value).is_file():
                # Found target file.
                print('Found target file : ' + filename)
                # もしテンポラリディレクトリが未作成なら、ここで作成する
                if not os.path.isdir(tmp_path + '/'):
                    os.mkdir(tmp_path + '/')

                # テンポラリディレクトリにここでコピーする。
                shutil.copy(filename, tmp_path + '/' + filename)

                # テンポラリディレクトリにコピー済のファイルを戻り値とする。
                return tmp_path + '/' + filename

    if is_only_booting == True:
        for cur_key in allow_option_file_only_booting:
            if key == cur_key.lower():
                print('match: ' + cur_key)

	        # Filter filename : exclude path string
                filename = pathlib.Path(value).name

            	# Check file exists
                if pathlib.Path(value).is_file():
 
                    # Found target file.
                    print('Found target file : ' + filename)
                    # もしテンポラリディレクトリが未作成なら、ここで作成する
                    if not os.path.isdir(tmp_path + '/'):
                        os.mkdir(tmp_path + '/')

                    # テンポラリディレクトリにここでコピーする。
                    shutil.copy(filename, tmp_path + '/' + filename)

                    # テンポラリディレクトリにコピー済のファイルを戻り値とする。
                    return tmp_path + '/' + filename

    # Not found.
    return False


# Main routine
def main():
    # Flags
    is_default_config=False
    have_default_section=False

    # 正しいオプションになっていないときは説明を出して終了する
    if len(sys.argv) != 3 and len(sys.argv) != 4:
        sys.stderr.write("Syntax : %s [merged_config] [cnf_file] (-b)\n"
                        % sys.argv[0])
        sys.exit(1)

    # -b (only_booting)フラグがオプションにあれば、フラグを立てる
    if len(sys.argv) == 4 and sys.argv[3] == '-b':
        is_default_config=True

    # Open Merged Config file and parse if exists
    merged_cfg = configparser.ConfigParser()
    merged_cfg.optionxform = lambda option: option.upper()
    if os.path.exists(sys.argv[1]) == True:
        merged_file = open(sys.argv[1], "r")
        merged_data = merged_file.read()
        merged_cfg.read_string(merged_data)
        merged_file.close()

    # Generate temporary path
    tmp_path = '/tmp/.cocon.files.' + str( random.randrange(99999) )
    #print('tmp : ' + tmp_path)

    # Open, read CNF file
    if os.path.exists(sys.argv[2]) == False:
        sys.stderr.write("CNF file not found.\n")
        sys.exit(1)
    in_file = open(sys.argv[2], "r")
    in_data = in_file.read()
    in_file.close()

    # Older version of OpenCocon CNF file isn't have [DEFAULT].
    # then insert top on data in this part.
    for line in in_data.splitlines():
        if line == '[DEFAULT]':
            have_default_section = True
    if have_default_section == False:
        in_data = "[DEFAULT]\r\n" + in_data

    # parse CNF file
    parse_cfg = configparser.ConfigParser()
    parse_cfg.read_string(in_data)

    # セクションごとにあるkey=valueに対し、ホワイトリストにあるものかを判定し、
    # もしあれば merged_cfg に書き込み（上書き）する。
    for cur_section in parse_cfg:
        print('section : ' + cur_section)

        # -b オプションがついており、かつ、"DEFAULT" セクションにある場合のみ、only_booting フラグをオンにする。
        only_booting = False
        if is_default_config == True and cur_section == 'DEFAULT':
            only_booting = True 

        for cur_key in parse_cfg[cur_section]:
            #print('key : ' + cur_key)
            #print('value : ' + parse_cfg[cur_section][cur_key])
            # key だけは configparser に通すと一律小文字にされるようだ

            # Boolean
            detect_output = pickup_bool_option(cur_key, parse_cfg[cur_section][cur_key], only_booting)
            if detect_output != False:
                if not cur_section in merged_cfg:
                    merged_cfg[cur_section] = {}
                merged_cfg[cur_section][cur_key.upper()] = detect_output

            # String
            detect_output = pickup_str_option(cur_key, parse_cfg[cur_section][cur_key], only_booting)
            if detect_output != False:
                if not cur_section in merged_cfg:
                    merged_cfg[cur_section] = {}
                merged_cfg[cur_section][cur_key.upper()] = detect_output

            # Integer
            detect_output = pickup_int_option(cur_key, parse_cfg[cur_section][cur_key], only_booting)
            if detect_output != False:
                if not cur_section in merged_cfg:
                    merged_cfg[cur_section] = {}
                merged_cfg[cur_section][cur_key.upper()] = str(detect_output)

            # File
            detect_output = pickup_file_option(cur_key, parse_cfg[cur_section][cur_key], only_booting, tmp_path)
            if detect_output != False:
                if not cur_section in merged_cfg:
                    merged_cfg[cur_section] = {}
                merged_cfg[cur_section][cur_key.upper()] = str(detect_output)


    # Write to Merged config file
    with open(sys.argv[1], 'w') as merged_file:
        merged_cfg.write(merged_file)

    sys.exit(0)


if __name__ == "__main__":
    main()

