#!/usr/bin/env python3

import os
import re
import yaml
import requests
import subprocess
from git import Repo
from pathlib import Path

class AURPackageUpdater:
    def __init__(self, config_path="aur-packages.yml"):
        with open(config_path, 'r') as f:
            self.config = yaml.safe_load(f)
        
        self.github_token = os.environ.get('GITHUB_TOKEN')
        self.headers = {
            'Authorization': f'token {self.github_token}',
            'Accept': 'application/vnd.github.v3+json'
        }

    def get_latest_version(self, package_config):
        owner, repo = package_config['github_repo'].split('/')
        
        if package_config['version_method'] == 'release':
            url = f'https://api.github.com/repos/{owner}/{repo}/releases/latest'
            response = requests.get(url, headers=self.headers)
            if response.status_code == 200:
                version = response.json()['tag_name']
        else:  # tag method
            url = f'https://api.github.com/repos/{owner}/{repo}/tags'
            response = requests.get(url, headers=self.headers)
            if response.status_code == 200:
                version = response.json()[0]['name']

        if 'version_pattern' in package_config:
            match = re.match(package_config['version_pattern'], version)
            if match:
                version = match.group(1)

        return version.lstrip('v')

    def get_current_version(self, pkgbuild_path):
        with open(pkgbuild_path, 'r') as f:
            content = f.read()
            match = re.search(r'pkgver=([^\n]+)', content)
            return match.group(1) if match else None

    def update_pkgbuild(self, package_name, package_config, new_version):
        pkgbuild_path = package_config['pkgbuild_path']
        
        # Run pre-update script if configured
        if 'pre_update_script' in package_config:
            subprocess.run([package_config['pre_update_script']], shell=True, check=True)

        # Update PKGBUILD
        with open(pkgbuild_path, 'r') as f:
            content = f.read()
        
        content = re.sub(
            r'pkgver=([^\n]+)',
            f'pkgver={new_version}',
            content
        )
        
        with open(pkgbuild_path, 'w') as f:
            f.write(content)

        # Generate .SRCINFO
        srcinfo_path = os.path.join(os.path.dirname(pkgbuild_path), '.SRCINFO')
        subprocess.run(['makepkg', '--printsrcinfo'], 
                      cwd=os.path.dirname(pkgbuild_path),
                      stdout=open(srcinfo_path, 'w'),
                      check=True)

        # Run post-update script if configured
        if 'post_update_script' in package_config:
            subprocess.run([package_config['post_update_script']], shell=True, check=True)

        return True

    def commit_and_push(self, package_name, new_version, pkgbuild_path):
        repo = Repo('.')
        repo.index.add([pkgbuild_path, f"{os.path.dirname(pkgbuild_path)}/.SRCINFO"])
        repo.index.commit(
            f"Update {package_name} to {new_version}",
            gpgsign=True
        )
        repo.remote().push()

    def run(self):
        for package_name, package_config in self.config['packages'].items():
            try:
                latest_version = self.get_latest_version(package_config)
                current_version = self.get_current_version(package_config['pkgbuild_path'])

                if latest_version != current_version:
                    print(f"Updating {package_name} from {current_version} to {latest_version}")
                    self.update_pkgbuild(package_name, package_config, latest_version)
                    self.commit_and_push(package_name, latest_version, package_config['pkgbuild_path'])
                else:
                    print(f"{package_name} is up to date ({current_version})")

            except Exception as e:
                print(f"Error processing {package_name}: {str(e)}")

if __name__ == "__main__":
    updater = AURPackageUpdater()
    updater.run() 