#!/usr/bin/env python3
import subprocess
import re

def get_latest_timestamp_tag():
    """
    Searches local images for tags matching the pattern:
    ghcr.io/troogs/fs-onboarding/server:YYYYMMDD-i
    and returns the latest timestamp tag (YYYYMMDD-i) based on date and index.
    """
    # Regular expression to match tags like: ghcr.io/troogs/fs-onboarding/server:20250328-1
    pattern = re.compile(r"ghcr\.io/troogs/fs-onboarding/server:(\d{8})-(\d+)$")
    
    # List images for the repository using the docker images command.
    result = subprocess.run(
        ["docker", "images", "ghcr.io/troogs/fs-onboarding/server", "--format", "{{.Repository}}:{{.Tag}}"],
        stdout=subprocess.PIPE,
        text=True,
        check=True
    )
    
    tags = result.stdout.strip().splitlines()
    timestamp_tags = []
    for tag in tags:
        m = pattern.match(tag)
        if m:
            date_part, index = m.groups()
            timestamp_tags.append((date_part, int(index)))
    
    if not timestamp_tags:
        return None
    
    # Choose the maximum tuple; lexicographical order works for YYYYMMDD and then by numeric index.
    latest = max(timestamp_tags, key=lambda x: (x[0], x[1]))
    return f"{latest[0]}-{latest[1]}"

def push_image(image_tag):
    """
    Pushes the specified image tag to the container registry.
    """
    print(f"Pushing image: {image_tag}")
    subprocess.run(["docker", "push", image_tag], check=True)

def main():
    # Retrieve the latest timestamp tag for the server image.
    server_timestamp = get_latest_timestamp_tag()
    
    if server_timestamp is None:
        print("Error: Could not find timestamp tagged images for server.")
        return
    
    common_timestamp = server_timestamp
    print(f"Common timestamp tag identified: {common_timestamp}")
    
    # Prepare the list of images to push: both 'latest' and the timestamp-tagged images.
    images_to_push = [
        "ghcr.io/troogs/fs-onboarding/server:latest",
        f"ghcr.io/troogs/fs-onboarding/server:{common_timestamp}"
    ]
    
    for image in images_to_push:
        push_image(image)

if __name__ == "__main__":
    main()
