#!/usr/bin/env python
#=========================================================================
# echo-progress [options] remainder
#=========================================================================
#
#  -h --help           Display this message
#     --nsteps         Total number of steps
#     --stepno         Which step is this
#     --verbose        Verbose mode (1=on,0=off)
#
# Used to print a progress indicator from makefile. Code adapted from:
#
#  https://stackoverflow.com/questions/451413
#
# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: MIT
# Author : Christopher Batten, NVIDIA
#

import argparse
import sys
import os
import re
import math
import datetime

#-------------------------------------------------------------------------
# Command line processing
#-------------------------------------------------------------------------

class ArgumentParserWithCustomError(argparse.ArgumentParser):
  def error( self, msg = "" ):
    if ( msg ): print("\n ERROR: %s" % msg)
    print("")
    file = open( sys.argv[0] )
    for ( lineno, line ) in enumerate( file ):
      if ( line[0] != '#' ): sys.exit(msg != "")
      if ( (lineno == 2) or (lineno >= 4) ): print( line[1:].rstrip("\n") )

def parse_cmdline():
  p = ArgumentParserWithCustomError( add_help=False )

  p.add_argument( "-h", "--help",    action="store_true" )
  p.add_argument(       "--stepno",  type=int, required=True )
  p.add_argument(       "--nsteps",  type=int, required=True )
  p.add_argument(       "--verbose", type=int, required=True )

  p.add_argument( "remainder", nargs=argparse.REMAINDER )

  opts = p.parse_args()
  if opts.help: p.error()
  return opts

#-------------------------------------------------------------------------
# Main
#-------------------------------------------------------------------------

def main():

  opts = parse_cmdline()

  # Read the prompt file

  if opts.verbose:
    sys.stdout.write("\n")

  nchars   = int(math.log(opts.nsteps, 10)) + 1
  progress = int(100 * opts.stepno / opts.nsteps)

  if opts.stepno == opts.nsteps:
    fmt_str = "[{:Xd}/{:Xd}](100)".replace("X", str(nchars))
  else:
    fmt_str = "[{:Xd}/{:Xd}]({:2d}%)".replace("X", str(nchars))

  sys.stdout.write(datetime.datetime.now().strftime("%H:%M"))
  sys.stdout.write(" ")
  sys.stdout.write(fmt_str.format(opts.stepno, opts.nsteps, progress))
  for item in opts.remainder:
    sys.stdout.write(" ")
    sys.stdout.write(item)
  sys.stdout.write("\n")

  if opts.verbose:
    sys.stdout.write("\n")

main()
