#!/usr/bin/env python3
import sys
import os
import re
import glob

print(sys.argv)
if len(sys.argv) == 1:
    print('usage: {} package.ipk'.format(sys.argv[0]))
    sys.exit(1)

for filename in sys.argv[1:]:
    m = re.match(r'((.*/)*)(.*)', filename)
    pkg = m.group(3)
    m = re.match(r'(.*)((.ipk)|(.deb))', filename)
    if m:
        pkg = m.group(1)

    os.system(f'rm -fr {pkg}')
    os.mkdir(pkg)
    os.mkdir(os.path.join(pkg, 'CONTROL'))
    
    abs_filename = os.path.abspath(filename)
    os.system(f'cd {pkg}; (ar -x {abs_filename} || tar zxf {abs_filename})')

    # Handle different possible extensions for the data archive
    data_files = glob.glob(f'{pkg}/data.tar.*')
    control_files = glob.glob(f'{pkg}/control.tar.*')

    if data_files:
        data_file = data_files[0]
        os.system(f'tar -axf {data_file} -C {pkg}')
    if control_files:
        control_file = control_files[0]
        os.system(f'tar -axf {control_file} -C {os.path.join(pkg, "CONTROL")}')

    # Clean up extracted archive files
    for data_file in data_files:
        os.remove(data_file)
    for control_file in control_files:
        os.remove(control_file)

    # Remove debian-binary if it exists
    debian_binary = os.path.join(pkg, 'debian-binary')
    if os.path.exists(debian_binary):
        os.remove(debian_binary)
