#!/usr/bin/python3
import re
import os
import sys
import importlib
from collections import defaultdict


if len(sys.argv) < 2:
    print(f"ERROR. usage: {os.path.basename(__file__)} <WWW_DIR>", file=sys.stderr)
    sys.exit(1)

# cd to project root
os.chdir(os.path.dirname(os.path.dirname(__file__)))

# load version.py; needlessly complicated alternative to "imp.load_source":
version_spec = importlib.util.spec_from_file_location('version', 'electrum/version.py')
version_module = importlib.util.module_from_spec(version_spec)
version_spec.loader.exec_module(version_module)

ELECTRUM_VERSION = version_module.ELECTRUM_VERSION
APK_VERSION = version_module.APK_VERSION
print(f"version: {ELECTRUM_VERSION}", file=sys.stderr)

dirname = sys.argv[1]

print(f"directory: {dirname}", file=sys.stderr)

download_page = os.path.join(dirname, "panel-download.html")
download_template = download_page + ".template"

with open(download_template) as f:
    download_page_str = f.read()

version = version_win = version_mac = version_android = ELECTRUM_VERSION
download_page_str = download_page_str.replace("##VERSION##", version)
download_page_str = download_page_str.replace("##VERSION_WIN##", version_win)
download_page_str = download_page_str.replace("##VERSION_MAC##", version_mac)
download_page_str = download_page_str.replace("##VERSION_ANDROID##", version_android)
download_page_str = download_page_str.replace("##VERSION_APK##", APK_VERSION)

# note: all dist files need to be listed here that we expect sigs for,
#       even if they are not linked to from the website
files = {
    "tgz": f"Electrum-{version}.tar.gz",
    "tgz_srconly": f"Electrum-sourceonly-{version}.tar.gz",
    "appimage": f"electrum-{version}-x86_64.AppImage",
    "mac": f"electrum-{version_mac}.dmg",
    "win": f"electrum-{version_win}.exe",
    "win_setup": f"electrum-{version_win}-setup.exe",
    "win_portable": f"electrum-{version_win}-portable.exe",
    "apk_arm64": f"Electrum-{APK_VERSION}-arm64-v8a-release.apk",
    "apk_armeabi": f"Electrum-{APK_VERSION}-armeabi-v7a-release.apk",
    "apk_x86_64": f"Electrum-{APK_VERSION}-x86_64-release.apk",
}

# default signers
signers = ['ThomasV', 'SomberNight']

# detect extra signers
list_dir = os.listdir('dist')
detected_sigs = defaultdict(set)
for f in list_dir:
    if f.endswith('.asc'):
        parts = f.split('.')
        signer = parts[-2]
        filename = '.'.join(parts[0:-2])
        detected_sigs[signer].add(filename)
for k, v in detected_sigs.items():
    if v == set(files.values()):
        if k not in signers:
            signers.append(k)

print(f"signers: {signers}", file=sys.stderr)

gpg_name = lambda x: 'sombernight_releasekey' if x=='SomberNight' else x
signers_list = ', '.join("<a href=\"https://raw.githubusercontent.com/spesmilo/electrum/master/pubkeys/%s.asc\">%s</a>"%(gpg_name(x), x) for x in signers)
download_page_str = download_page_str.replace("##signers_list##", signers_list)

for k, filename in files.items():
    path = "dist/%s"%filename
    assert filename in list_dir
    link = "https://download.electrum.org/%s/%s"%(version, filename)
    download_page_str = download_page_str.replace("##link_%s##" % k, link)
    download_page_str = download_page_str.replace("##sigs_%s##" % k, link + '.asc')


# download page has been constructed from template; now insert it into index.html
index_html_path = os.path.join(dirname, "index.html")
with open(f"{index_html_path}.template") as f:
    index_html_str = f.read()

index_html_str = index_html_str.replace("##DOWNLOAD_PAGE##", download_page_str)

with open(index_html_path, 'w') as f:
    f.write(index_html_str)
