#!/usr/bin/env python3
import os
import subprocess
import sys
import tarfile
import lzma
import gzip

def main():
    option = sys.argv[1]
    filename = sys.argv[2]
    if option in ['cf', '-cf']:
        if filename.endswith('.tar'):
            files = sys.argv[3:-1]
            with tarfile.open(filename, 'w') as tar:
                for file in files:
                    print(f"add {file} to {filename}")
                    tar.add(file)
        else:
            print("File must end With .tar")
            sys.exit(1)
    elif option in ['cJf', '-cJf']:
        if filename.endswith('.tar.xz'):
            files = sys.argv[3:-1]
            name, archive, suffix = os.path.splitext(filename)
            newname = f"{name}.{archive}"
            with tarfile.open(newname, 'w:xz') as tar:
                for file in files:
                    print(f"add {file} to {filename}")
                    tar.add(file)
        else:
            print("File must end With .tar.xz")
            sys.exit(1)
    elif option in ['czf', '-czf']:
        if filename.endswith('.tar.gz'):
            files = sys.argv[3:-1]
            name, archive, suffix = os.path.splitext(filename)
            newname = f"{name}.{archive}"
            with tarfile.open(newname, 'w:gz') as tar:
                for file in files:
                    print(f"add {file} to {filename}")
                    tar.add(file)
        else:
            print("File must end With .tar.gz")
            sys.exit(1)
    elif option in ['xf', '-xf']:
        if filename.endswith('.tar'):
            with tarfile.open(filename, 'r') as tar:
                tar.extractall('.')
        else:
            print("File must end With .tar")
            sys.exit(1)
    elif option in ['xvf', '-xvf']:
        if filename.endswith('.tar.xz'):
            with tarfile.open(filename, 'r:xz') as tar:
                tar.extractall('.')
        else:
            print("File must end With .tar.xz")
            sys.exit(1)
    elif option in ['xzf', '-xzf']:
        if filename.endswith('.tar.gz'):
            with tarfile.open(filename, 'r:gz') as tar:
                tar.extractall('.')
        else:
            print("File must end With .tar.gz")
            sys.exit(1)
    else:
        text = """Usage: pstar [option] [filename] <files>
Options:
    -cf         Pack a Tar archive
    -cJf        Pack a Tar archive with xz
    -czf        Pack a Tar archive with gzip
    -xf         Depack a Tar archive
    -xvf        Depack a Tar archive with xz
    -xzf        Depack a Tar archive with gzip
"""
        print(text)