#!/usr/bin/env python3

"""
A script to automatically write docs to /docs. Currently it generates
os.rst, a feature table of OS features.

Requires Python 3.

(C) 2015 Simon Warta (Kullo GmbH)

Botan is released under the Simplified BSD License (see license.txt)
"""

# global
import argparse
import glob
import os
import sys

# Assume this script is in botan/src/scripts
botan_root = os.path.join(os.path.dirname(sys.argv[0]), "..", "..")

# locale
sys.path.append(botan_root)
from configure import OsInfo

parser = argparse.ArgumentParser(description="")
parser.add_argument('--verbose', dest='verbose', action='store_const',
                    const=True, default=False,
                    help='Verbose output (default: false)')
args = parser.parse_args()

def update_os():
    PAGE_TITLE="Botan OS information"
    TABLE_TITLE="OS Features"

    files = []
    files += glob.glob(botan_root + '/src/build-data/os/*.txt')
    files.sort()

    if len(files) == 0:
        print("No info.txt files found.")
        sys.exit(1)

    f1 = open(os.path.join(botan_root, 'doc', 'os.rst'), 'w+')    

    all_features = set()
    oss = {}

    for filename in files:
        o = OsInfo(filename)
        oss[o.basename] = o
        all_features |= set(o.target_features)
        if args.verbose:
            print(o.basename)
            print(o.target_features)

    featurelist = list(all_features)
    featurelist.sort()
    oslist = list(oss.keys())
    oslist.sort()

    if args.verbose:
        print(featurelist)

    print(PAGE_TITLE, file=f1)
    print("========================================", file=f1)
    print("", file=f1)

    print(TABLE_TITLE, file=f1)
    print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^", file=f1)
    print("", file=f1)

    print("A summary of OS features as defined in ``src/build-data/os``.", file=f1)
    print("", file=f1)

    print("::", file=f1)
    print("", file=f1)
    for o in oslist:
        print("  %s: %s" % (o[0:1], o), file=f1)
    print("", file=f1)

    print('.. csv-table::', file=f1)
    print('   :header: "Feature", "' + '", "'.join([o[0:1] for o in oslist]) + '"', file=f1)
    print('', file=f1)

    for f in featurelist:
        line = '   "' + f + '"'
        for o in oslist:
            line += ', "'
            line += 'X' if f in oss[o].target_features else ' '
            line += '"'
        print(line, file=f1)
    print("", file=f1)
    print(".. note::", file=f1)
    print("   This file is auto generated by ``src/scripts/%s``. Dont modify it manually."
                    % os.path.basename(sys.argv[0]), file=f1)

if __name__ == '__main__':
    update_os()
