import subprocess
import datetime
import os


def get_git_revision():
  try:
    rev = (
      subprocess.check_output(
        ["git", "rev-parse", "--short", "HEAD"],
        cwd=os.path.dirname(os.path.abspath(__file__)),
      )
      .decode("ascii")
      .strip()
    )
    return rev
  except (subprocess.CalledProcessError, FileNotFoundError):
    return "unknown"


def generate_header(output_path):
  revision = get_git_revision()
  build_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

  content = f"""// Auto-generated by components/version/build_version.py    
#ifndef COMPONENTS_VERSION_VERSION_H_IN_
#define COMPONENTS_VERSION_VERSION_H_IN_

#define URGE_GIT_REVISION "{revision}"
#define URGE_BUILD_DATE "{build_date}"

#endif  //! COMPONENTS_VERSION_VERSION_H_IN_
"""

  os.makedirs(os.path.dirname(output_path), exist_ok=True)
  with open(output_path, "w") as f:
    f.write(content)


if __name__ == "__main__":
  import sys

  if len(sys.argv) != 2:
    print("Usage: python build_version.py <output_path>")
    sys.exit(1)
  generate_header(sys.argv[1])
