#! /usr/bin/env python3

import argparse
import sys
import logging
import subprocess
from pathlib import Path
from datetime import datetime

logger = logging.getLogger(__name__)

def main() -> int:
    # Handle program arguments
    ap = argparse.ArgumentParser(prog='normalize-timestamp', description='Normalizes timestamps on files')
    ap.add_argument("--mode", help="Normalization mode", choices=["earliest", "latest"], default="earliest")
    ap.add_argument('files', help='Files to normalize', nargs='+', type=Path)
    ap.add_argument('-v', '--verbose', help='Enable verbose logging', action='store_true')
    args = ap.parse_args()

    # Configure logging
    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format='%(levelname)s:	%(message)s',
    )
    
    # Iter files
    for file in args.files:
        
        # Read the timestamps
        creation_time = datetime.fromtimestamp(file.stat().st_ctime)
        modification_time = datetime.fromtimestamp(file.stat().st_mtime)
        
        # Normalize the timestamps
        if args.mode == "earliest":
            new_time = min(creation_time, modification_time)
        else:
            new_time = max(creation_time, modification_time)
            
        # Set the new timestamps
        logger.info(f"Setting {args.mode} timestamp on {file}")
        subprocess.run(["touch", "-t", new_time.strftime("%Y%m%d%H%M.%S"), file])

    return 0

if __name__ == "__main__":
    sys.exit(main())