#!/usr/bin/env python3
import argparse, re, subprocess
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
MAIN = ROOT / "Cargo.toml"
MACROS = ROOT / "macros" / "Cargo.toml"

def read_version(path):
    return re.search(r'^version = "([^"]+)"', path.read_text(), re.M).group(1)

def bump(v):
    _major, minor, patch = map(int, v.split("."))
    if patch >= 9:
        return f"1.{minor + 1}.0"
    return f"1.{minor}.{patch + 1}"

def set_version(path, old, new):
    text = path.read_text().replace(f'version = "{old}"', f'version = "{new}"', 1)
    text = text.replace(f'tw2-jsonrpc-macros = {{ version = "{old}"', f'tw2-jsonrpc-macros = {{ version = "{new}"')
    path.write_text(text)

parser = argparse.ArgumentParser()
parser.add_argument("--first", action="store_true")
args = parser.parse_args()

old = read_version(MAIN)
new = old if args.first else bump(old)

set_version(MACROS, read_version(MACROS), new)
set_version(MAIN, old, new)
subprocess.run(["cargo", "publish"], cwd=ROOT / "macros", check=True)
subprocess.run(["cargo", "publish"], cwd=ROOT, check=True)
