#!/usr/bin/python3

"""Setup of data and documentation"""

import argparse
import sys
from pathlib import Path
import subprocess
import parentdir # pylint: disable=W0611
import Documentation
from Externals import get_database_object
from GitVersion import Git
from Import import find_all_configs
import Persistence.log as log

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--verbose', '-v',
                    dest='verbose',
                    help='Output lots of stuff',
                    required=False,
                    default=3,
                    action='count')
args = parser.parse_args()
args.verbose = 50 - args.verbose * 10

log.basicConfig(level=args.verbose, style='{')
log_ = log.getLogger('setup', fmt='{name}:{levelname} {message}')

output_dir = Path('output')
dump_dir = output_dir / 'dumps'
config_dir = Path('data')
doc_source = Path('doc')
Path.mkdir(dump_dir, parents=True, exist_ok=True)

database = get_database_object('readwrite')
database.purge_data()

configurations = find_all_configs(config_dir)
if configurations is None:
    sys.exit(1)
navilinks = Documentation.navilink_list(Git().describe('--dirty'))
dumplinks = Documentation.dumplink_list(configurations)

Documentation.create_documentation(navilinks, doc_source, output_dir)
Documentation.create_dump_mainpage(navilinks, dumplinks, dump_dir)
dRM = Documentation.MarkdownDoc(Path("data") / 'README.md', navilinks)
dRM.write(output_dir / 'data.html')
sRM = Documentation.MarkdownDoc(Path("sources") / 'README.md', navilinks)
sRM.write(output_dir / 'sources.html')

licpage = Documentation.Licenses(doc_source / 'copyright.md', navilinks)

for cid, config in configurations.items():
    log_.info("Processing file %s", cid)
    is_default = True
    for a in config.access:
        database.insert_source(a, cid, is_default)
        is_default = False # only first one.
    for mht in config.magic_hashtags:
        database.insert_magic_hashtag(cid, mht)
    for dl in config.data_list:
        if not database.insert_datalist(dl, cid):
            sys.exit(1)
    Documentation.dump_source(config, dumplinks, navilinks, database, dump_dir)
    licpage.add_source(config)
licpage.write(output_dir / 'copyright.html')
Documentation.dump_blacklist(dumplinks, navilinks, database, dump_dir)
database.close_sucessfully()

subprocess.run(['chmod', '-R', 'ug=rwX,o=rX', str(output_dir)], check=False)
target_dir = Path('/var/www/ds100/')
avatar_dir = Path('/var/www/avatar/')
if target_dir.exists():
    subprocess.run(['rsync', '-a', str(output_dir) + "/", str(target_dir)], check=False)
    subprocess.run(['rsync', '-a', str(doc_source / 'bot.css'), str(target_dir)], check=False)
else:
    log_.warning('Not copying documentation')
if avatar_dir.exists():
    subprocess.run(['rsync', '-a', str(doc_source / 'avatar.svg'), str(avatar_dir / 'ds100.svg')],
    check=False)
else:
    log_.warning('Not copying avatar')

log_.info("Done")
