import json
import time
import os
import sys


# set default options
options = {
  'autoconfirm': False,
  'help': False,
  'days': 30,
  'path': 'service.cfg'}

# check passed options
for arg in sys.argv[1:]:
  if arg[:2] == '-h':
    options['help'] = True
  elif arg[:2] == '-y':
    options['autoconfirm'] = True
  elif arg[:3] == '-d=':
    try:
      days = int(arg[3:])
      options['days'] = days
    except:
      print(f'Invalid DAYS -> {arg}')
      exit(1)
  elif arg[:3] == '-p=':
    path = arg[3:]
    if not os.path.isfile(path):
      print(f'Invalid PATH -> {arg}')
      exit(1)
    else:
      options['path'] = path
  else:
    print(f'Unknown argument -> {arg}')
    exit(1)

# print help message
if options['help']:
  print('Purge audio and json files older than certain age')
  print('Usage:')
  print('purge_audio [options]')
  print('  -d=<days>   everything older will be deleted')
  print('              default is 30 days')
  print('  -h          show help')
  print('  -p=<path>   specify mic0 configuration file path')
  print('              default is service.cfg in current directory')
  print('  -y          autoconfirm')
  print('              default is off')
  exit(0)


# main function

# calculate and display cutoff timestamp
current_time = time.mktime(time.localtime())
purge_time = current_time - (options['days'] * 24 * 60 * 60)
purge_timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(purge_time))
print(f'Purging data older than {purge_timestamp}')

confirm = 'Y' if options['autoconfirm'] else input('Are you sure? Y/N ').upper()

if confirm == 'Y':
  print('Reading configuration...')
  json_data = {}
  try:
    cfg = open(options['path'])
    json_data = json.load(cfg)
    cfg.close()
  except:
    print('Bad configuration file')
    exit(1)
  print('Searching for data paths...')
  paths_to_purge = []
  for k, v in json_data['devices'].items():
    try:
      paths_to_purge.append(v['work_dir'])
    except:
      pass
    try:
      paths_to_purge.append(v['backup_dir'])
    except:
      pass
  paths_to_purge = [p for p in paths_to_purge if len(p)]
  print('Paths found:')
  for p in paths_to_purge:
    print(f'  {p}')

  print('Checking files...')
  purge_list = []
  for p in paths_to_purge:
    purged_files = 0
    unknown_files = 0
    left_files = 0
    file_list = []
    try:
      print(f'  {p}')
      file_list = os.listdir(p)
    except:
      print('    invalid path, skipping')
      continue
    for f in file_list:
      f_name, f_ext = f.split('.')
      f_ext = f_ext.upper()
      file_timestamp = None
      if f_ext in ["WAV", "WAVE", "FLAC", "MP3", "OGG", "JSON"]:
        # remove audio file
        file_timestamp = f_name[-15:]
        # check if file has to be removed
        file_time = time.mktime(time.strptime(file_timestamp, "%Y%m%d_%H%M%S"))
        if file_time <= purge_time:
          # mark for removal
          purge_list.append(f'{p}/{f}')
          purged_files += 1
        else:
          left_files += 1
      else:
        # unknown file
        unknown_files += 1
    print(f'    purge/leave/unknown {purged_files}/{left_files}/{unknown_files}')

  print(f'Purged file list contains {len(purge_list)} files')
  removed_files = 0
  confirm = 'Y' if options['autoconfirm'] or len(purge_list) == 0 else input('Are you sure? Y/N ').upper()
  if confirm == 'Y':
    for f in purge_list:
      try:
        os.remove(f)
        removed_files += 1
      except:
        pass
  print(f'Removed files: {removed_files}')
else:
  print('User cancelled, exiting...')
  print('Removed files: 0')
