#!/usr/bin/env python3

import argparse, os, re, sys

parser = argparse.ArgumentParser()
parser.add_argument('-e', '--expiration', action='store_true')
# For backwards compatibility for SR where version is not fixed but the most recent
parser.add_argument('-v', '--version', action='store_true')
# For backwards compatibility for ORS which need to load 2021 sdr driver first
parser.add_argument('-o', '--old-version', action='store_true')
args = parser.parse_args()

amarisoft_dir = "{{ amarisoft_dir }}"
try:
  lte_version = sorted(filter(lambda x: re.match(r"v[0-9]{4}-[0-9]{2}-[0-9]{2}", x), os.listdir(amarisoft_dir)))[-1][1:]
except (FileNotFoundError, IndexError):
  lte_version = '0000-00-00'
try:
  old_lte_version = sorted(filter(lambda x: re.match(r"v2021-[0-9]{2}-[0-9]{2}", x), os.listdir(amarisoft_dir)))[-1][1:]
except (FileNotFoundError, IndexError):
  old_lte_version = '0000-00-00'
lte_expiration = "9999-99-99"
try:
  for filename in os.listdir(amarisoft_dir + '/.amarisoft'):
    if filename.endswith('.key'):
      with open(os.path.join(amarisoft_dir + '/.amarisoft', filename), 'r') as f:
        f.seek(260)
        for l in f:
          if l.startswith('version='):
            lte_expiration = l.split('=')[1].strip()
except FileNotFoundError:
  pass

if args.expiration:
  print(lte_expiration, end='')
elif args.version:
  print(lte_version, end='')
elif args.old_version:
  print(old_lte_version, end='')
