#!/usr/bin/env python3
"""gps-check.py: report whether JPEG, PNG or WebP files carry GPS coordinates.

Usage: python3 gps-check.py photo1.jpg [photo2.png ...]
Looks in the Exif block (JPEG APP1, PNG eXIf, WebP EXIF) and in XMP (exif:GPSLatitude).
Exit code: 0 = no GPS in any file, 1 = GPS found in at least one file, 2 = a file could not be read.
Standard library only. It reads files; it never changes them.
"""
import re
import struct
import sys

TYPE_SIZE = {1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 7: 1, 9: 4, 10: 8}


def read_ifd(tiff, offset, endian):
    """Return {tag: (type, count, value_offset_or_bytes)} for the IFD at offset."""
    entries = {}
    if offset + 2 > len(tiff):
        return entries
    (n,) = struct.unpack_from(endian + "H", tiff, offset)
    for i in range(n):
        pos = offset + 2 + i * 12
        if pos + 12 > len(tiff):
            break
        tag, typ, count = struct.unpack_from(endian + "HHI", tiff, pos)
        size = TYPE_SIZE.get(typ, 1) * count
        if size <= 4:
            data = tiff[pos + 8:pos + 8 + size]
        else:
            (off,) = struct.unpack_from(endian + "I", tiff, pos + 8)
            data = tiff[off:off + size]
        entries[tag] = (typ, count, data)
    return entries


def rationals(data, endian, count):
    out = []
    for i in range(count):
        if len(data) < (i + 1) * 8:
            return None
        num, den = struct.unpack_from(endian + "II", data, i * 8)
        out.append(num / den if den else 0.0)
    return out


def exif_gps(tiff):
    """Return (lat, lon) from a TIFF/Exif block, ('tags', None) if only GPS tags without coordinates, or None."""
    if len(tiff) < 8 or tiff[:2] not in (b"II", b"MM"):
        return None
    endian = "<" if tiff[:2] == b"II" else ">"
    (ifd0,) = struct.unpack_from(endian + "I", tiff, 4)
    ptr = read_ifd(tiff, ifd0, endian).get(0x8825)
    if not ptr:
        return None
    (gps_off,) = struct.unpack_from(endian + "I", ptr[2], 0)
    gps = read_ifd(tiff, gps_off, endian)
    if not all(k in gps for k in (1, 2, 3, 4)):
        return ("tags", None) if gps else None
    lat = rationals(gps[2][2], endian, 3)
    lon = rationals(gps[4][2], endian, 3)
    if not lat or not lon:
        return ("tags", None)
    la = lat[0] + lat[1] / 60 + lat[2] / 3600
    lo = lon[0] + lon[1] / 60 + lon[2] / 3600
    if gps[1][2][:1] == b"S":
        la = -la
    if gps[3][2][:1] == b"W":
        lo = -lo
    return (round(la, 5), round(lo, 5))


def xmp_gps(xmp):
    text = xmp.decode("utf-8", "replace")
    lat = re.search(r'GPSLatitude(?:>|=")\s*([^<"]+)', text)
    lon = re.search(r'GPSLongitude(?:>|=")\s*([^<"]+)', text)
    if lat and lon:
        return (lat.group(1).strip(), lon.group(1).strip())
    return None


def blocks(data):
    """Yield ('exif'|'xmp', bytes) for every metadata block found in the file."""
    if data[:2] == b"\xff\xd8":
        pos = 2
        while pos + 4 <= len(data) and data[pos] == 0xFF:
            marker = data[pos + 1]
            if marker == 0xDA or marker == 0xD9:
                break
            (length,) = struct.unpack_from(">H", data, pos + 2)
            seg = data[pos + 4:pos + 2 + length]
            if marker == 0xE1 and seg.startswith(b"Exif\x00\x00"):
                yield "exif", seg[6:]
            elif marker == 0xE1 and seg.startswith(b"http://ns.adobe.com/xap/1.0/\x00"):
                yield "xmp", seg[29:]
            pos += 2 + length
    elif data[:8] == b"\x89PNG\r\n\x1a\n":
        pos = 8
        while pos + 8 <= len(data):
            (length,) = struct.unpack_from(">I", data, pos)
            kind = data[pos + 4:pos + 8]
            body = data[pos + 8:pos + 8 + length]
            if kind == b"eXIf":
                yield "exif", body
            elif kind == b"iTXt" and body.startswith(b"XML:com.adobe.xmp"):
                yield "xmp", body
            pos += 12 + length
    elif data[:4] == b"RIFF" and data[8:12] == b"WEBP":
        pos = 12
        while pos + 8 <= len(data):
            kind = data[pos:pos + 4]
            (length,) = struct.unpack_from("<I", data, pos + 4)
            body = data[pos + 8:pos + 8 + length]
            if kind == b"EXIF":
                yield "exif", body[6:] if body.startswith(b"Exif\x00\x00") else body
            elif kind == b"XMP ":
                yield "xmp", body
            pos += 8 + length + (length & 1)
    else:
        raise ValueError("not a JPEG, PNG or WebP file")


def check(path):
    with open(path, "rb") as fh:
        data = fh.read()
    if not data:
        raise ValueError("file is empty")
    found = []
    for kind, body in blocks(data):
        if kind == "exif":
            res = exif_gps(body)
            if res and res[0] == "tags":
                found.append("Exif has GPS tags but no coordinates")
            elif res:
                found.append("Exif GPS %s, %s" % res)
        else:
            res = xmp_gps(body)
            if res:
                found.append("XMP GPS %s, %s" % res)
    return found


def main(paths):
    if not paths:
        print("usage: python3 gps-check.py photo.jpg [more files]", file=sys.stderr)
        return 2
    status = 0
    for path in paths:
        try:
            found = check(path)
        except (OSError, ValueError, struct.error) as err:
            print("%s: cannot read (%s)" % (path, err))
            status = 2
            continue
        if found:
            print("%s: GPS FOUND, %s" % (path, "; ".join(found)))
            if status == 0:
                status = 1
        else:
            print("%s: no GPS found" % path)
    return status


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
