#!/usr/bin/python3

import contextlib
import os
import sys
import subprocess
import tempfile

from aptsources.distro import get_distro


codename=get_distro().codename
URI='http://fake.mirror.private.com/ubuntu'
SOURCESLIST=f'deb {URI} {codename} main'
SOURCESLISTFILE=f'/etc/apt/sources.list.d/archive_uri-http_fake_mirror_private_com_ubuntu-{codename}.list'

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

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

   cmd = f'add-apt-repository {yes} {noupdate} {param} {archive}'
   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 = f'add-apt-repository {remove} {yes} {noupdate} {param} {archive}'
   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 PARAM in ['-U', '--uri', '']:
   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(URI, PARAM, YES, NOUPDATE, REMOVE, LOCALE)

for PARAM in ['-S', '--sourceslist', '']:
   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(SOURCESLIST, PARAM, YES, NOUPDATE, REMOVE, LOCALE)

sys.exit(0)
