#!/usr/bin/env python3
import subprocess
from datetime import datetime

def image_exists_on_server(full_image_tag):
    """
    Check if a Docker image exists on the remote server.
    Uses 'docker manifest inspect' which returns 0 if the image is found.
    Debug output is printed for inspection.
    """
    try:
        subprocess.run(
            ["docker", "manifest", "inspect", full_image_tag],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            check=True
        )
        print(f"[DEBUG] Found image on server: {full_image_tag}")
        return True
    except subprocess.CalledProcessError as e:
        print(f"[DEBUG] Image not found on server: {full_image_tag}. Error: {e.stderr.strip()}")
        return False

def get_date_tag(base_tag, today):
    """
    Given the base image tag (e.g. 'ghcr.io/troogs/fs-onboarding/server')
    and today's date, find the first available tag in the format YYYYMMDD-i
    that is not already present on the remote server.
    """
    i = 1
    while True:
        date_tag = f"{today}-{i}"
        full_tag = f"{base_tag}:{date_tag}"
        print(f"[DEBUG] Checking tag {date_tag}: {full_tag}")
        
        if not image_exists_on_server(full_tag):
            print(f"[DEBUG] Tag {date_tag} is available for use.")
            return date_tag
        else:
            print(f"[DEBUG] Tag {date_tag} is already in use. Incrementing index.")
        i += 1

def main():
    # Get today's date in YYYYMMDD format.
    today = datetime.now().strftime("%Y%m%d")
    print(f"Using date tag base: {today}")
    
    base_image_tag = "ghcr.io/troogs/fs-onboarding/server"
    date_tag = get_date_tag(base_image_tag, today)
    print(f"Common date tag determined: {date_tag}")

    # Build command using the common date tag for the server image.
    command = (
        f"docker build -f dockerfile.server "
        f"-t {base_image_tag}:latest "
        f"-t {base_image_tag}:{date_tag} ..\\"
    )
    print(f"Executing: {command}")
    subprocess.run(command, shell=True, check=True)

if __name__ == "__main__":
    main()
