#! /usr/bin/python3
# vim: set filetype=python:

# rot-jpg: losslessly rotate JPEG files

# Copyright (C) 2019-2026 by Brian Lindholm.  This file is part of the
# littleutils utility set.
#
# The rot-jpg utility is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3, or (at your option) any later version.
#
# The rot-jpg utility is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# the littleutils.  If not, see <https://www.gnu.org/licenses/>.

import concurrent.futures, getopt, os, signal, subprocess, sys, tempfile

### PREP SIGNAL HANDLER ###
interrupted = False
def handler(signum, frame):
    global interrupted
    interrupted = True
for signal_VAL in (signal.SIGHUP, signal.SIGINT, signal.SIGPIPE, signal.SIGQUIT, signal.SIGTERM):
    signal.signal(signal_VAL, handler)

### GET INPUT ARGUMENTS ###
# print online help
def usage(rc: int) -> None:
    print('rot-jpg 1.4.0')
    print('usage: rot-jpg [-f filelist] [-F(ast)] [-h(elp)] [-l(eft)] [-p(ipe)] [-q(uiet)]')
    print('         [-r(ight)] [-t(ouch)] [-T threads] [-u(pside-down)] filename ...')
    sys.exit(rc)
# load list of files
def load_list_from_file() -> None:
    if not os.path.isfile(opt_f):  # abort if file does not exist
        print('rot-jpg error: file list %s does not exist' % opt_f, file=sys.stderr)
        sys.exit(1)
    try:
        FILE = open(opt_f, 'r')
    except:  # abort if file cannot be opened for read
        print('rot-jpg error: file list %s cannot be opened' % opt_f, file=sys.stderr)
        sys.exit(1)
    filelist.extend(FILE.read().splitlines())
    FILE.close()
# load list of files from stdin
def load_list_from_stdin() -> None:
    filelist.extend(sys.stdin.read().splitlines())
    sys.stdin.close()
# set defaults
filelist = []
angle = None   # angle of JPEG rotation
opt_f = None   # file containing list of files to process
opt_F = False  # run fast by skipping optimization
opt_p = False  # read list of files to process from stdin
opt_q = False  # be quiet
opt_t = False  # "touch" re-written files to preserve timestamps
opt_T = None   # requested thread-count
# get command-line options
try:
    opts, filelist = getopt.getopt(sys.argv[1:], 'f:FhlpqrtT:u', 'help')
except getopt.error as msg:
    # print help if bad opts used, then quit
    print(msg)
    usage(1)
# parse options
for o, v in opts:
    if o in ('-h', '--help'): usage(0)
    elif o == '-f': opt_f = str(v)
    elif o == '-F': opt_F = True
    elif o == '-l': angle = '270'
    elif o == '-p': opt_p = True
    elif o == '-q': opt_q = True
    elif o == '-r': angle = '90'
    elif o == '-t': opt_t = True
    elif o == '-T': opt_T = int(v)
    elif o == '-u': angle = '180'
# load file list from file and/or stdin if requested
if opt_f != None: load_list_from_file()
if opt_p: load_list_from_stdin()
# make sure we have at least one file to process
if len(filelist) == 0:
    if (not opt_f) and (not opt_p): usage(1)
    sys.exit(0)
# make sure an angle has been specified
if angle == None:
    print('rot-jpg error: one of -l, -r, or -u must be specified')
    usage(1)
# remove leading './' and trim list to unique items
filelist = [x.removeprefix('./') for x in filelist]
seen = set()
unique_filelist = [x for x in filelist if x not in seen and (seen.add(x) or True)]
# pick a reasonable default if thread-count is unspecified
if opt_T == None: opt_T = max(1, min(os.cpu_count() // 2, len(unique_filelist)))

### HAND-OFF to OPT-JPG (if fast operation not requested) ###
if opt_F == False:
    TMPFILE = tempfile.SpooledTemporaryFile(mode='w+')
    for filename in unique_filelist: print(filename, file=TMPFILE)
    TMPFILE.seek(0)
    args = ['opt-jpg', '-p', '-T', str(opt_T), '-r', angle]
    if opt_q: args.append('-q')
    if opt_t: args.append('-t')
    subprocess.run(args, stdin=TMPFILE)
    TMPFILE.close()
    sys.exit(0)

### MAIN PROGRAM ###
# preload image types and depths
image_type = {}
def preload_image_types() -> None:
    TMPFILE = tempfile.SpooledTemporaryFile(mode='w+')
    for filename in unique_filelist: print(filename, file=TMPFILE)
    TMPFILE.seek(0)
    IMAGSIZE = subprocess.run(['imagsize', '-p'], stdin=TMPFILE, capture_output=True, text=True)
    TMPFILE.close()
    lines = IMAGSIZE.stdout.splitlines()
    for line in lines:
        field = line.split('\t')
        image_type[field[0]] = field[-1].removeprefix('type=')
# rotate the JPEG file
def process_file(filename: str) -> None:
    # abort if file does not exist
    if interrupted: return
    if not os.path.isfile(filename):
        if not opt_q: print('rot-jpg error: %s is not a file' % filename, file=sys.stderr)
        return
    # skip zero-length files
    if os.path.getsize(filename) == 0: return
    # skip non-JPEG images
    if filename in image_type:
        if not image_type[filename].startswith('jpg'):
            if not opt_q: print('rot-jpg error: %s is not a JPEG image' % filename, file=sys.stderr)
            return
    # grab initial timestamp if required
    if opt_t: timestamp = os.path.getmtime(filename)
    # run jpegtran
    args = ['jpegtran', '-trim', '-rotate', angle, filename]
    TMPJPG = subprocess.run(args, capture_output=True, text=False)
    if interrupted: return
    # abort if output is of zero size
    if len(TMPJPG.stdout) == 0:
        if not opt_q: print('rot-jpg error: %s is a bad JPEG file' % filename, file=sys.stderr)
        return
    # re-write the file
    try:
        FILE = open(filename, 'wb')
    except:
        print('rot-jpg error: cannot write results to %s' % filename, file=sys.stderr)
        return
    FILE.write(TMPJPG.stdout)
    FILE.close()
    if not opt_q: print('%s: rotated by %s' % (filename, angle), file=sys.stderr)
    if opt_t: os.utime(filename, (timestamp, timestamp))

# process files
preload_image_types()
if opt_T < 2:
    for filename in unique_filelist:
        if interrupted: break
        process_file(filename)
else:
    with concurrent.futures.ThreadPoolExecutor(max_workers=opt_T) as executor:
        executor.map(process_file, unique_filelist)
