#!/usr/bin/env python3
# FIXME remove release flag?
import argparse
import json
import os
import subprocess
import sys
from pathlib import Path
from subprocess import check_call, check_output

# right, specifying id in manifest doesn't seem to work
# AMO responds with: Server response: Duplicate add-on ID found. (status: 400)
IDS = {
    'firefox'       : '{07c6b8e1-94f7-4bbf-8e91-26c0a8992ab5}',
    'chrome'        : 'kdmegllpofldcpaclldkopnnjjljoiio',
}


TARGETS = [
    'chrome',
    'firefox',
]


THISDIR = Path(__file__).absolute().parent


# FFS json doesn't allow newlines, need to put \n, which makes everything unreadable
AMO_METADATA = {
  "summary": {
    "en-US": "Recall which pages you already visited, why and in which context"
  },
  "description": {
    "en-US": """
Promnesia is a browser extension (Chrome/Firefox/Firefox mobile) which provides a sidebar which complements browser history with some enhanced features.

TLDR: it lets you explore your browsing history in context: where you encountered it, in chat, on Twitter, on Reddit, or just in one of the text files on your computer.
This is unlike most modern browsers, where you can only see when you visited the link.

It allows you to answer different questions about the current web page:

- have I been here before? When?
- why have I bookmarked it?
- how did I get on it? Which page has led to it?
- who sent me this link? Can I just jump to the message?
- which links on this page have I already explored?
- which posts from this blog page have I already read?

*NOTE*: to get the most benefits from the extension, you also need to set up a supplementary service. You can find the instructions [here](https://github.com/karlicoss/promnesia#setup).
"""
  },
  "requires_payment": False,
  "categories": {
    # see: https://mozilla.github.io/addons-server/topics/api/categories.html
    "firefox": ["bookmarks", "search-tools"]
  },
  "support_email": {
    "en-US": "karlicoss.dev@gmail.com"
  },
  "homepage": {
    "en-US": "https://github.com/karlicoss/promnesia"
  },
  "version": {
    "license": "MIT",
    "approval_notes": """
You can find up-to-date extension code here https://github.com/karlicoss/promnesia/tree/master/extension

The build instructions assume that the zip file with source code is in =/path/to/extension-source-firefox.zip= (on the HOST system).
*Make sure to replace it with the actual path to the source code zip file.*

To build you need *Ubuntu 24.04/Noble* and *Node 24*. The easiest way to build cleanly would be a Docker container:

```
# on the HOST system: cleanup previous container -- if it didn't exist in the first place, it will show an error, ignore it
docker rm -f extension_build

# on the HOST system: create the container
docker create --name extension_build -it ubuntu:noble /bin/bash

# on the HOST system: put the sources into the container
docker cp /path/to/extension-source-firefox.zip extension_build:/extension-source-firefox.zip

# on the HOST system: start the container
docker start -i extension_build
```

After that build the addon (run these commands INSIDE the container if you choose to do it with Docker):

```
$ apt update && apt install -y git curl unzip
$ curl -fsSL https://deb.nodesource.com/setup_24.x | bash -
$ DEBIAN_FRONTEND=noninteractive apt install -y nodejs
$ unzip extension-source-firefox.zip -d extension
$ cd extension
$ npm install
$ ./build --firefox --release --lint --publish=skip
```


The final artifact will be in =/extension/dist/artifacts/firefox/promnesia-<version>.zip= (INSIDE the container).

If you need to get it back onto the HOST system (e.g. to test in the browser), run on the HOST system (e.g. in a separate terminal):

docker cp extension_build:/extension/dist/artifacts/firefox/promnesia-<version>.zip

This will copy it into the current directory on the HOST system.
"""
  }
}



npm = "npm.cmd" if sys.platform == "win32" else "npm"


def main() -> None:
    p = argparse.ArgumentParser()
    p.add_argument('--release', action='store_true', help="Use release flavor of build")
    p.add_argument('--watch'  , action='store_true')
    p.add_argument('--lint'   , action='store_true')
    p.add_argument('--publish', choices=['listed', 'unlisted', 'skip'], help="Publish on chrome web store/addons.mozilla.org")
    p.add_argument('--v3', action='store_const', const='3', dest='manifest')
    p.add_argument('--v2', action='store_const', const='2', dest='manifest')

    tg = p.add_mutually_exclusive_group(required=True)
    tg.add_argument('--target', type=str, choices=TARGETS)
    for b in TARGETS:
        tg.add_argument('--' + b, action='store_const', const=b, dest='target')
    args = p.parse_args()
    target = args.target

    assert target is not None

    manifest = args.manifest or '3'

    assert not (target == 'chrome' and manifest == '2'), "chrome doesn't support manifest v2 anymore"

    base_ext_dir = THISDIR / 'dist'
    ext_dir = (base_ext_dir / target).resolve() # webext can't into symlinks
    # sadly no way to specify zip name in the regex..
    artifacts_dir = (base_ext_dir / 'artifacts' / target).resolve()
    def webext(*args, silent: bool=False, method=subprocess.check_call):
        return method([
            npm, 'run', *(['--silent'] if silent else []), 'web-ext',
            '--',
            '--source-dir'   , ext_dir,
            '--artifacts-dir', artifacts_dir,
            *args,
        ])

    def webext_lint() -> None:
        # first run for human readable output
        webext('lint', method=subprocess.run)

        # second run actually checks (annoying)
        res = webext(
            'lint',
            '--output=json',
            '--no-config-discovery',  # prevent it from printing "Applying config file" to stdout
            silent=True,  # otherwise craps in stdout
            method=lambda cmd: subprocess.run(cmd, check=False, stdout=subprocess.PIPE, text=True),
        )
        j = json.loads(res.stdout)
        errors = j['errors']
        if len(errors) == 0:
            return

        assert target == 'chrome' and manifest == '3', (target, manifest)  # only chrome v3 allowed to have errors at this point

        assert len(errors) == 1, errors
        [err] = errors
        d = 'The "/background/service_worker" manifest property must be paired with use of "/background/scripts" property for Firefox compatibility'
        assert d in err['description'], err
        print(f"NOTE: skipping '{d}' for chrome -- this is false positive in webext lint", file=sys.stderr)

    env = {
        'TARGET' : target,
        'RELEASE': 'YES' if args.release else 'NO',
        'PUBLISH': 'YES' if args.publish is not None else 'NO',
        'MANIFEST': manifest,
        'EXT_ID' : IDS[target],
        **os.environ,
    }

    if args.watch:
        check_call([npm, 'run', 'watch'], env=env, cwd=str(THISDIR))  # todo exec instead?
        return

    check_call([npm, 'run', 'build'], env=env, cwd=str(THISDIR))

    if 'firefox' in target:
        amo_metadata = THISDIR / 'amo-metadata.json'
        amo_metadata.write_text(json.dumps(AMO_METADATA, indent=2))

    if args.lint:
        # TODO --self-hosted
        # TODO warnings as errors??
        webext_lint()

        # TODO move somewhere more appropriate..
        webext('build', '-o')  # -o overwrites existing artifact

    if args.release:
        assert args.lint  # TODO not sure..

    if args.publish not in {None, 'skip'}:
        # 'skip' mode is useful to build exactly same build as for the store, but without actually uploading
        assert args.lint
        assert args.release

        repo_status = check_output(['git', 'status', '--porcelain', '--untracked-files=no'], text=True)
        assert len(repo_status) == 0, repo_status  # ensure repo is clean
        source_zip = base_ext_dir / f'extension-source-{target}.zip'
        check_call(['git', 'archive', 'HEAD', '--output', source_zip], cwd=THISDIR)  # cwd so we only package the extension

        if 'firefox' in target:
            # see https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#web-ext-sign
            assert ('WEB_EXT_API_KEY' in os.environ) and ('WEB_EXT_API_SECRET' in os.environ), "env variables must be set to publish"
            check_call([
                npm, 'run', 'web-ext',
                '--',
                'sign',
                '--channel', args.publish,
                '--source-dir', ext_dir,
                '--artifacts-dir', artifacts_dir,
                # this will be passed automatically from env
                # '--api-key'      , ...,
                # '--api-secret'   , ...,
                # seems like webext sign requires addon id to be in manifest now
                '--amo-metadata' , amo_metadata,
                '--upload-source-code', source_zip,
            ])
        elif target == 'chrome':
            assert args.publish == 'listed'  # no notion of unlisted on chrome store?

            # see https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#web-ext-sign
            assert ('CLIENT_ID' in os.environ) and ('CLIENT_SECRET' in os.environ) and ('REFRESH_TOKEN' in os.environ), "env variables must be set to publish"
            check_call([
                npm, 'run', 'chrome-webstore-upload',
                '--',
                # 'upload'/'publish'
                # NOTE: without command would do both
                '--source'        , ext_dir,
                # this will be passed automatically from env
                # '--client-id'     , ...,
                # '--client-secret' , ...,
                # '--refresh--token', ...,
                '--extension-id'  , IDS[target],
                # todo trusted testers?
            ])
        else:
            raise RuntimeError(f"{target} is not supported for publishing yet")

if __name__ == '__main__':
    main()
