#!/usr/bin/env python

import sys
from os import path
from PyPDF2 import PdfFileReader, PdfFileWriter


def print_info(pdf):
    pdf = PdfFileReader(pdf)
    info = pdf.getDocumentInfo()
    print(f'Author: {info.author}\n'
          f'Creator: {info.creator}\n'
          f'Producer: {info.producer}\n'
          f'Subject: {info.subject}\n'
          f'Title: {info.title}\n'
          f'Number of pages: {pdf.getNumPages()}')


def rotate(angle, pdfin, pdfout):
    reader = PdfFileReader(pdfin)
    writer = PdfFileWriter()
    for page in reader.pages:
        writer.addPage(page.rotateClockwise(angle))
    with open(pdfout, 'wb') as f:
        writer.write(f)


def split(pdfin, pdfout):
    reader = PdfFileReader(pdfin)
    name, ext = path.splitext(pdfout)
    for i, page in enumerate(reader.pages):
        writer = PdfFileWriter()
        writer.addPage(page)
        with open(f'{name}-{i}{ext}', 'wb') as f:
            writer.write(f)


def merge(pdfin, pdfout):
    writer = PdfFileWriter()
    for pdf in pdfin:
        reader = PdfFileReader(pdf)
        for page in reader.pages:
            writer.addPage(page)
    with open(pdfout, 'wb') as f:
        writer.write(f)


if __name__ == '__main__':
    action = sys.argv[1]
    if action == 'info':
        print_info(sys.argv[2])
    elif action == 'rotate':
        rotate(int(sys.argv[2]), sys.argv[3], sys.argv[4])
    elif action == 'split':
        split(sys.argv[2], sys.argv[3])
    elif action == 'merge':
        merge(sys.argv[2:-1], sys.argv[-1])
    else:
        raise ValueError(f'unknown action {action}')
