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

# opt-gif: losslessly optimize GIF files

# Copyright (C) 2004-2026 by Brian Lindholm.  This file is part of the
# littleutils utility set.
#
# The opt-gif 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 opt-gif 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('opt-gif 1.4.0')
    print('usage: opt-gif [-f filelist] [-h(elp)] [-p(ipe)] [-q(uiet)] [-t(ouch)]')
    print('         [-T threads] 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('opt-gif 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('opt-gif 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 = []
opt_a = False  # use arithmetic encoding
opt_f = None   # file containing list of files to process
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:], 'af:hpqtT:', '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 == '-a': opt_a = True
    elif o == '-f': opt_f = str(v)
    elif o == '-p': opt_p = True
    elif o == '-q': opt_q = True
    elif o == '-t': opt_t = True
    elif o == '-T': opt_T = int(v)
# 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)
# 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)))

### 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=')
# optimize the GIF 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('opt-gif error: %s is not a file' % filename, file=sys.stderr)
        return
    # skip zero-length files
    origsize = os.path.getsize(filename)
    if origsize == 0: return
    # skip non-GIF images
    if filename in image_type:
        if image_type[filename] != 'gif':
            if not opt_q: print('opt-gif error: %s is not a GIF image' % filename, file=sys.stderr)
            return
    # grab initial timestamp if required
    if opt_t: timestamp = os.path.getmtime(filename)
    # run gifsicle
    args = ['gifsicle', '--careful', '-O3', '--no-warnings', filename]
    TMPGIF = subprocess.run(args, capture_output=True, text=False)
    if interrupted: return
    newsize = len(TMPGIF.stdout)
    # abort if output is of zero size
    if newsize == 0:
        if not opt_q: print('opt-gif error: failed gifsicle processing of %s' % filename, file=sys.stderr)
        return
    # ensure that new file is smaller
    if newsize < origsize:
        try:
            FILE = open(filename, 'wb')
        except:
            print('opt-gif error: cannot write results to %s' % filename, file=sys.stderr)
            return
        FILE.write(TMPGIF.stdout)
        FILE.close()
        if not opt_q: print('%s: %d vs. %d' % (filename, origsize, newsize), file=sys.stderr)
        if opt_t: os.utime(filename, (timestamp, timestamp))
    elif not opt_q:
        print('%s: unchanged' % filename, file=sys.stderr)

# 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)
