#!/bin/bash

# compresspdf
# Version: 0.1.0
# Author: dabruh
# GitLab: https://gitlab.com/dabruh
# GitHub: https://github.com/dabruh
#
# Simply compress a PDF

SCRIPT_NAME="$(basename -- "$0")"
FORCE=false

function usage() {
    echo "Usage: $SCRIPT_NAME [OPTIONS]"
    echo
    echo "Options:"
    echo "  -h           Display help."
    echo "  -i [FILE]    Input file."
    echo "  -o [FILE]    Output file."
    echo "  -f           Overwrite existing output file."
}

while getopts ":i:o:fh" arg; do
    case $arg in
    i) INPUT_FILE_PATH="$(realpath "$OPTARG")" ;;
    o) OUTPUT_FILE_PATH=$OPTARG ;;
    f) FORCE=true ;;
    h)
        usage
        exit 0
        ;;
    :)
        echo "$SCRIPT_NAME: Must supply a value with -$OPTARG." >&2
        usage
        exit 1
        ;;
    ?)
        echo "Invalid option: -${OPTARG}."
        echo
        usage
        exit 2
        ;;
    esac
done

if [ -z "$INPUT_FILE_PATH" ]; then
    echo "$SCRIPT_NAME: Missing mandatory option -i." >&2
    usage
    exit 3
elif [ -z "$OUTPUT_FILE_PATH" ]; then
    INPUT_FILE_DIR="${INPUT_FILE_PATH%/*}"
    INPUT_FILE_FULL_NAME="${INPUT_FILE_PATH##*/}"
    INPUT_FILE_NOEXT_NAME="${INPUT_FILE_FULL_NAME%.*}"
    INPUT_FILE_EXT="${INPUT_FILE_PATH##*.}"
    OUTPUT_FILE_PATH="$INPUT_FILE_DIR/$INPUT_FILE_NOEXT_NAME-min.$INPUT_FILE_EXT"
fi

if [ -f "$OUTPUT_FILE_PATH" ]; then
    echo "File exists: $OUTPUT_FILE_PATH" >&2

    if $FORCE; then
        echo "Removing: $OUTPUT_FILE_PATH" >&2
        rm "$OUTPUT_FILE_PATH" || exit 11
    else
        exit 12
    fi
fi

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/prepress -dNOPAUSE -dQUIET -dBATCH -sOutputFile="$OUTPUT_FILE_PATH" "$INPUT_FILE_PATH" || exit 21
echo "$OUTPUT_FILE_PATH"
