#!/usr/bin/env python3
"""Generate .SRCINFO from PKGBUILD for AUR publishing.

This script is used by the publish-to-aur GitHub Actions workflow because
makepkg/pacman are not available on Ubuntu runners.

Run it from the directory that contains PKGBUILD:
    python3 gen_srcinfo.py
"""

import pathlib
import re

pkgbuild = pathlib.Path("PKGBUILD").read_text()


def extract(var):
    m = re.search(rf"^{var}=(.+)", pkgbuild, re.MULTILINE)
    return m.group(1).strip().strip("'\"") if m else ""


pkgname = extract("pkgname")
pkgver = extract("pkgver")
pkgrel = extract("pkgrel")
pkgdesc = extract("pkgdesc").strip("'\"")
arch_line = re.search(r"^arch=\((.+)\)", pkgbuild, re.MULTILINE).group(1)
archs = re.findall(r"'([^']+)'", arch_line)
url = extract("url")
license_ = re.search(r"^license=\('([^']+)'\)", pkgbuild, re.MULTILINE).group(1)
depends_m = re.search(r"^depends=\((.+?)\)", pkgbuild, re.MULTILINE | re.DOTALL)
depends = re.findall(r"'([^']+)'", depends_m.group(1)) if depends_m else []
provides_m = re.search(r"^provides=\('([^']+)'\)", pkgbuild, re.MULTILINE)
provides = [provides_m.group(1)] if provides_m else []
conflicts_m = re.search(r"^conflicts=\('([^']+)'\)", pkgbuild, re.MULTILINE)
conflicts = [conflicts_m.group(1)] if conflicts_m else []

src_x86 = re.search(r'^source_x86_64=\("([^"]+)"\)', pkgbuild, re.MULTILINE)
src_aarch = re.search(r'^source_aarch64=\("([^"]+)"\)', pkgbuild, re.MULTILINE)
sha_x86 = re.search(r"^sha256sums_x86_64=\('([^']+)'\)", pkgbuild, re.MULTILINE)
sha_aarch = re.search(r"^sha256sums_aarch64=\('([^']+)'\)", pkgbuild, re.MULTILINE)

lines = []
lines.append("# Generated by gen_srcinfo.py")
lines.append(f"pkgbase = {pkgname}")
lines.append(f"\tpkgdesc = {pkgdesc}")
lines.append(f"\tpkgver = {pkgver}")
lines.append(f"\tpkgrel = {pkgrel}")
lines.append(f"\turl = {url}")
for a in archs:
    lines.append(f"\tarch = {a}")
lines.append(f"\tlicense = {license_}")
for d in depends:
    lines.append(f"\tdepends = {d}")
for p in provides:
    lines.append(f"\tprovides = {p}")
for c in conflicts:
    lines.append(f"\tconflicts = {c}")
if src_x86:
    lines.append(f"\tsource_x86_64 = {src_x86.group(1)}")
if sha_x86:
    lines.append(f"\tsha256sums_x86_64 = {sha_x86.group(1)}")
if src_aarch:
    lines.append(f"\tsource_aarch64 = {src_aarch.group(1)}")
if sha_aarch:
    lines.append(f"\tsha256sums_aarch64 = {sha_aarch.group(1)}")
lines.append("")
lines.append(f"pkgname = {pkgname}")

pathlib.Path(".SRCINFO").write_text("\n".join(lines) + "\n")
print(".SRCINFO generated:")
print("\n".join(lines))
