#!/bin/bash
set -euo pipefail

cd "$(dirname "$(readlink -f "$0")")"

latest=$(curl -s https://product-details.mozilla.org/1.0/firefox_versions.json \
  | awk -F'"' '/LATEST_FIREFOX_VERSION/ {print $4}')

current=$(grep -oP '^pkgver=\K.*' PKGBUILD)

if [[ "$latest" == "$current" ]]; then
  echo "Already up-to-date: $latest"
  exit 0
fi

echo "Updating: $current -> $latest"

sed -i "s/^pkgver=$current\$/pkgver=$latest/" PKGBUILD

archive_sha=$(curl -sL "https://archive.mozilla.org/pub/firefox/releases/$latest/SHA256SUMS" \
  | awk '/linux-x86_64\/ru\/firefox-'"$latest"'\.tar\.xz$/ {print $1}')

[[ -n "$archive_sha" ]] && sed -i "s/^sha256sums_x86_64=('[^']*')$/sha256sums_x86_64=('$archive_sha')/" PKGBUILD \
  || echo "Warning: could not fetch SHA256 for archive"

# update local source sha256sums
python3 <<'PYEOF'
import re

with open('PKGBUILD') as f:
    content = f.read()

# extract source files
m = re.search(r'^source=\(([^)]*)\)', content, re.MULTILINE)
files = []
if m:
    for line in m.group(1).split('\n'):
        fname = line.strip().strip("'\"").strip()
        if fname:
            files.append(fname.replace('$_pkgname', 'firefox'))

if files:
    import subprocess
    result = subprocess.run(['sha256sum'] + files, capture_output=True, text=True)
    shas = [line.split()[0] for line in result.stdout.strip().split('\n') if line]

    # find and replace sha256sums block
    new_block = "sha256sums=("
    for s in shas:
        new_block += "\n            '" + s + "'"
    new_block += ")"

    def replace(m):
        return new_block

    content = re.sub(r'^sha256sums=\([^)]*\)', replace, content, count=1, flags=re.MULTILINE)
    with open('PKGBUILD', 'w') as f:
        f.write(content)
PYEOF

echo "Done. New version: $latest"