# sfile — super file: detailed file header decoding
CC      ?= gcc
CFLAGS  ?= -O2 -Wall -Wextra -std=c11
PREFIX  ?= /usr/local

SRC     = src/sfile.c
LIB_SRC = src/sfile_lib.c src/geotag.c
LIB_HDR = src/sfile.h src/geotag.h
LIB_OBJ = sfile_lib.o geotag.o
LIB_A   = libsfile.a
LIB_SO  = libsfile.so.1.1.0
LIB_SONAME = libsfile.so.1
BIN     = sfile
GEN     = tools/gen_formats.py
TABLE   = src/formats.h src/formats.json

SCAR_SRC = src/scar.c
SCAR_BIN = scar

all: $(BIN) $(SCAR_BIN) lib

$(BIN): $(SRC) $(LIB_OBJ) src/formats.h
	$(CC) $(CFLAGS) -o $@ $(SRC) $(LIB_OBJ)

# libsfile — the decode engine as a linkable library (see docs/library.md).
# The CLI links the same objects, so library and CLI results agree.
# geotag.c is part of the library: sfile_decode_file fills the geotag
# fields of sfile_result via geotag_scan().
lib: $(LIB_A) libsfile.so

sfile_lib.o: src/sfile_lib.c $(LIB_HDR) src/formats.h
	$(CC) $(CFLAGS) -c -o $@ src/sfile_lib.c

geotag.o: src/geotag.c src/geotag.h
	$(CC) $(CFLAGS) -c -o $@ src/geotag.c

$(LIB_A): $(LIB_OBJ)
	ar rcs $@ $(LIB_OBJ)

$(LIB_SO): $(LIB_SRC) $(LIB_HDR) src/formats.h
	$(CC) $(CFLAGS) -fPIC -shared -Wl,-soname,$(LIB_SONAME) -o $@ $(LIB_SRC)

libsfile.so: $(LIB_SO)
	ln -sf $(LIB_SO) $(LIB_SONAME)
	ln -sf $(LIB_SONAME) libsfile.so

# scar — file carver built on sfile's format table (src/scar.c).
# Links zlib: gzip members are sized by inflating the stream.
# (The file target below also answers `make scar`.)
$(SCAR_BIN): $(SCAR_SRC) src/formats.h src/footers.h
	$(CC) $(CFLAGS) -o $@ $(SCAR_SRC) -lz

# stag / sgeo -- geotag tools. They do NOT link against sfile: they run
# the sfile binary and parse its "Geotagging:" section through the
# client seam in src/geotag_client.c (see docs/geotag-contract.md).
stag: src/stag.c src/geotag_client.c src/geotag_client.h
	$(CC) $(CFLAGS) -o $@ src/stag.c src/geotag_client.c -lm

sgeo: src/sgeo.c src/geotag_client.c src/geotag_client.h
	$(CC) $(CFLAGS) -o $@ src/sgeo.c src/geotag_client.c -lpng -lcurl -lm

# Regenerate the format table from the collected reference code.
# (Requires tools/all_formats.cpp; overrides live in tools/overrides.json.)
table: $(GEN) tools/all_formats.cpp
	python3 $(GEN) tools/all_formats.cpp src/formats.json src/formats.h

test: $(BIN)
	./tests/run_tests.sh

test-json: $(BIN)
	python3 tests/test_json.py

test-lib: lib
	./tests/test_lib.sh

test-geotag: $(BIN)
	python3 tests/geotag/run_geotag_tests.py

test-scar: $(SCAR_BIN)
	python3 tests/test_scar.py

install: $(BIN) $(SCAR_BIN) lib
	mkdir -p $(PREFIX)/bin $(PREFIX)/lib $(PREFIX)/include
	cp $(BIN) $(PREFIX)/bin/
	cp $(SCAR_BIN) $(PREFIX)/bin/
	cp $(LIB_A) $(PREFIX)/lib/
	cp -P $(LIB_SO) $(LIB_SONAME) libsfile.so $(PREFIX)/lib/
	cp $(LIB_HDR) $(PREFIX)/include/
	chmod 755 $(PREFIX)/bin/$(BIN) $(PREFIX)/bin/$(SCAR_BIN)

clean:
	rm -f $(BIN) $(SCAR_BIN) stag sgeo *.o $(LIB_A) $(LIB_SO) $(LIB_SONAME) libsfile.so

.PHONY: all table test test-json test-lib test-geotag test-scar install clean lib
