#!/usr/bin/python3

import argparse
import subprocess

parser = argparse.ArgumentParser()
parser.add_argument(
    "--dont-sort", help="Don't sort the PDFs, respect what received", action='store_true'
)
parser.add_argument("filepaths", metavar='filepath', nargs="+", help="The PDFs to convert.")
args = parser.parse_args()

if not all(x.lower().endswith(".pdf") for x in args.filepaths):
    print("All indicated files must be PDFs.")
    exit()

# produce the output name
output_chars = []
for input_chars in zip(*args.filepaths):
    if len(set(input_chars)) == 1:
        output_chars.append(list(set(input_chars))[0])
    else:
        break
output = "{}-joined.pdf".format("".join(output_chars))


if args.dont_sort:
    filepaths = args.filepaths
else:
    filepaths = sorted(args.filepaths)

cmd = ['pdftk'] + filepaths + ['cat', 'output', output]
subprocess.run(cmd)
