#!/bin/bash

#1. Instructions and escape

echo "Instructions. This script will inject/overwrite metadata to image files with data from C+F."

echo "This script assumes you have: "

echo " 1) Shot, developed and scanned X rolls of film. Format (jpg, raw, etc) is irrelevant."

echo " 2) Recorded parameters for each roll with C+F."

echo " 3) Exported data from C+F to a working directory resulting in one directory per roll."

echo " 4) Each directory has a parameter file 'film.json' and some jpegs. Delete the jpegs."

echo " 5) Scanned images from 1) are copied into the proper roll directory from C+F."

echo " 6) Each image file has a simple name starting with 0.ext, 1.ext, etc"

echo " 7) Copied this script into the active 'Roll XXX' C+F directory and run within that directory './CFedit.sh'."

echo "Complete running the script by answering 'GO' below, 'NO' if you are not ready and start over."

echo "Injected image files can then be imported into your archival system, Apple Photo, etc and processed on."

echo "Repeat with the next directory."

echo "Tip: Keep a copy of each source roll and images, and a source copy of this script in the bottom of your working dir."

echo

read -r -p "Ready to GO? " answer

echo

if [ "$answer" != "GO" ]; then

echo "Aborting script."

exit 1

fi

echo

echo "1) Running in directory: " $PWD

# 2 & 3. Read the JSON cleanly and pair files exactly to what exists in the directory

echo

echo "2) Syncing JSON metadata mapping to current directory files..."

echo

python3 - << 'EOF'

import json

import os

import glob

# Load original JSON structure

with open('film.json', 'r') as f:

data = json.load(f)

# Define all target extensions to find (handles any case like .JPG, .HEIC, .arw)

#target_extensions = ['*.jpg', '*.JPG', '*.jpeg', '*.JPEG', '*.arw', '*.ARW', '*.raw', '*.RAW', '*.heic', '*.HEIC', '*.tif']

target_extensions = ['*.jpg', '*.jpeg', '*.arw', '*.raw', '*.heic','*.tif']

images = []

for ext in target_extensions:

# Match lowercase extensions

images.extend(glob.glob(ext))

# Match uppercase extensions (e.g., .JPG, .HEIC)

images.extend(glob.glob(ext.upper()))

# Sort files alphabetically/numerically to ensure correct frame order mapping

images = sorted(list(set(images)))

if not images:

print("Error: No matching image files (.jpg, .jpeg, .arw, .raw, .heic, .tif) found in this directory!")

exit(1)

# Dynamically map existing records to local image files

for index, record in enumerate(data):

if index < len(images):

# Maps entry directly to the exact file path found on disk

record["SourceFile"] = f"./{images[index]}"

# Overwrite database with updated clean mapping

with open('film.json', 'w') as f:

json.dump(data, f, indent=2)

print(f"3) Successfully matched {min(len(data), len(images))} metadata entries to local files.")

EOF

# 4. Run ExifTool on local matches

echo

echo "4) Writing EXIF metadata to files..."

exiftool -m -overwrite_original -json="film.json" .

echo

echo " *** DONE! ***"

echo