#!/usr/bin/env python3

import argparse
import os
from subprocess import call
import re
import sys

parser = argparse.ArgumentParser(prog='./dev')
subparsers = parser.add_subparsers(metavar='<command>', title='commands')

DOCKER_RUN = ['docker', 'run', '--init', '-it', '--rm', '-v',
              os.getcwd() + ':/src:cached', '-w=/src', 'node:18.12.1-alpine']

def start(args, remaining):
    call(DOCKER_RUN + ['yarn', 'start'])
parser_start = subparsers.add_parser('start',
    help='Initialize the development environment')
parser_start.set_defaults(func=start)

def sh(args, remaining):
    call(DOCKER_RUN + ['sh'])
parser_sh = subparsers.add_parser('sh', help='Bring up a shell')
parser_sh.set_defaults(func=sh)

def yarn(args, remaining):
    call(DOCKER_RUN + ['yarn'] + remaining or [])
parser_yarn = subparsers.add_parser('yarn', help='Run a yarn command')
parser_yarn.set_defaults(func=yarn)

def format(args, remaining):
    rc = call(DOCKER_RUN + ['yarn', 'format'])
    exit(rc)
parser_format = subparsers.add_parser('format',
    help='Format the code with Prettier')
parser_format.set_defaults(func=format)

def lint(args, remaining):
    rc = call(DOCKER_RUN + ['yarn', 'lint'])
    exit(rc)
parser_lint = subparsers.add_parser('lint', help='Lint the code with ESLint')
parser_lint.set_defaults(func=lint)

def release(args, remaining):
    try:
        new_version = input('What is the new version? ')
        if not re.match(r'\d+\.\d+\.\d+', new_version):
            print('Bad version format (should be x.y.z)')
            exit(1)
        if input('Did you update the manifest version [y/n]? ').lower() != 'y':
            exit(1)
        if input('Did you update the changelog [y/n]? ').lower() != 'y':
            exit(1)
    except (KeyboardInterrupt, EOFError):
        exit(0)

    rc = call(DOCKER_RUN + ['yarn', 'release'])
    if rc:
        exit(rc)

    print('\nUpload the new ZIP to the Chrome Web Store:')
    print('https://chrome.google.com/webstore/developer/edit/jngmmiaolbliepfphdnelgfcclpnkoja')
    print('\nAnd to Mozilla Add-ons:')
    print('https://addons.mozilla.org/en-US/developers/addon/pawblock/edit')
    print('\nAnd to GitHub:')
    print('https://github.com/dguo/pawblock/releases')
parser_release = subparsers.add_parser('release', help='Help release an update')
parser_release.set_defaults(func=release)

def test(args, remaining):
    rc = call(DOCKER_RUN + ['yarn', 'test'])
    exit(rc)
parser_test = subparsers.add_parser('test', help='test the code')
parser_test.set_defaults(func=test)

if len(sys.argv) > 1:
    args, remaining = parser.parse_known_args()
    args.func(args, remaining)
else:
    parser.print_help()
