#!/usr/bin/python3

import contextlib
import os
import sys
import subprocess
import tempfile

from aptsources.distro import get_distro

codename=get_distro().codename
SOURCESLISTFILE=f'/etc/apt/sources.list.d/ubuntu-support-team-ubuntu-software-properties-autopkgtest-{codename}.list'
TRUSTEDFILE='/etc/apt/trusted.gpg.d/ubuntu-support-team-ubuntu-software-properties-autopkgtest.gpg'
PPANAME='ubuntu-support-team/software-properties-autopkgtest'

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

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

   cmd = f'add-apt-repository {yes} {noupdate} {param} {ppa}'
   try:
      subprocess.check_call(cmd.split(), env=env)
   except subprocess.CalledProcessError:
      if not param and not ppa.startswith('ppa:'):
         # When using 'line' instead of --ppa, the 'ppa:' prefix is required
         return
      raise

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

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

   with tempfile.TemporaryDirectory() as homedir:
      cmd = f'gpg -q --homedir {homedir}  --no-default-keyring --keyring {TRUSTEDFILE} --fingerprint'
      subprocess.check_call(cmd.split(), env=env)

   cmd = f'add-apt-repository {remove} {yes} {noupdate} {param} {ppa}'
   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)

   if not os.path.exists(TRUSTEDFILE):
      print("trusted.gpg should not have been removed, but it was: %s" % TRUSTEDFILE)
      sys.exit(1)


for PPAFORMAT in [f'{PPANAME}', f'{PPANAME}'.replace('/', '/ubuntu/')]:
   for PPA in [f'{PPAFORMAT}', f'ppa:{PPAFORMAT}']:
      for PARAM in ['-P', '--ppa', '']:
         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(PPA, PARAM, YES, NOUPDATE, REMOVE, LOCALE)

sys.exit(0)

