#!/usr/bin/env python3

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

def update_pkgbuild(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(package_name, new_version, pkgbuild_path, repo=None, fs=os):
    """
    Commit and push changes to the PKGBUILD and .SRCINFO files.
    
    Args:
        package_name: Name of the package being updated
        new_version: New version string
        pkgbuild_path: Path to the PKGBUILD file
        repo: Git repository object (defaults to current directory)
        fs: Path operations interface (defaults to os)
    """
    if repo is None:
        repo = Repo('.')
        
    srcinfo_path = fs.join(fs.dirname(pkgbuild_path), '.SRCINFO')
    
    # Add files to git
    repo.index.add([pkgbuild_path, srcinfo_path])
    
    # Commit changes
    repo.index.commit(
        f"Update {package_name} to {new_version}",
        gpgsign=True
    )
    
    # Push changes
    repo.remote().push()

def main():
    with open('aur-packages.yml', 'r') as f:
        config = yaml.safe_load(f)

    updates = json.loads(os.environ['UPDATES_LIST'])
    
    for update in updates:
        package_name = update['name']
        package_config = config['packages'][package_name]
        new_version = update['latest']
        
        try:
            print(f"Updating {package_name} to {new_version}")
            update_pkgbuild(package_name, package_config, new_version)
            commit_and_push(package_name, new_version, package_config['pkgbuild_path'])
            print(f"Successfully updated {package_name}")
        except Exception as e:
            print(f"Error updating {package_name}: {str(e)}")

if __name__ == "__main__":
    main() 