#!/usr/bin/python3

import contextlib
import os
import sys
import subprocess

from softwareproperties.cloudarchive import RELEASE_MAP
from aptsources.distro import get_distro

codename = get_distro().codename
uca_releases = list(filter(lambda r: RELEASE_MAP[r] == codename, RELEASE_MAP.keys()))

if not uca_releases:
   print("No UCA releases available for this Ubuntu release")
   sys.exit(77)

def run_test(caname, uca, param, yes, noupdate, remove, locale):
   env = os.environ.copy()
   if locale:
      env['LC_ALL'] = locale

   SOURCESLISTFILE=f'/etc/apt/sources.list.d/cloudarchive-{caname}.list'

   with contextlib.suppress(FileNotFoundError):
      os.remove(SOURCESLISTFILE)

   cmd = 'apt-get -q -y remove ubuntu-cloud-keyring'
   subprocess.run(cmd.split(), stderr=subprocess.DEVNULL, env=env)

   cmd = f'add-apt-repository {yes} {noupdate} {param} {uca}'
   subprocess.check_call(cmd.split(), env=env)

   if not os.path.exists(SOURCESLISTFILE) or os.path.getsize(SOURCESLISTFILE) == 0:
      print("Missing/empty sources.list file: %s" % SOURCESLISTFILE)
      sys.exit(1)

   cmd = 'dpkg-query -l ubuntu-cloud-keyring'
   subprocess.check_call(cmd.split(), env=env)

   cmd = f'add-apt-repository {remove} {yes} {noupdate} {param} {uca}'
   subprocess.check_call(cmd.split(), env=env)

   if os.path.exists(SOURCESLISTFILE):
      print("sources.list file not removed: %s" % SOURCESLISTFILE)
      with open(SOURCESLISTFILE) as f:
         print(f.read())
      sys.exit(1)

for CANAME in uca_releases:
   for UCA in [f'{CANAME}', f'cloud-archive:{CANAME}', f'uca:{CANAME}']:
      for PARAM in ['-C', '--cloud', '']:
         for YES in ['-y', '--yes']:
            for NOUPDATE in ['-n', '--no-update', '']:
               for REMOVE in ['-r', '--remove']:
                  for LOCALE in ['', 'C', 'C.UTF-8']:
                     run_test(CANAME, UCA, PARAM, YES, NOUPDATE, REMOVE, LOCALE)

sys.exit(0)
