#!/bin/sh

# filter_android_messages.sh
# 2025-12-12
# by Gernot Walzl

# https://f-droid.org/packages/com.github.tmo1.sms_ie/

MESSAGES_IN=$1
ADDRESS=$2
MESSAGES_FILTERED="$(basename "$MESSAGES_IN" .zip)_$(echo $ADDRESS | sed 's/+//').zip"

set -e

if [ ! -r "$MESSAGES_IN" ]; then
  exit 1
fi

mkdir orig
(
  cd orig || exit 1
  unzip "../$MESSAGES_IN"
)

mkdir -p filtered/data
grep "\"address\":\"$ADDRESS\"" orig/messages.ndjson \
  > filtered/messages.ndjson
cat filtered/messages.ndjson \
  | sed -n 's/.*"_data":"\([^"]*\)".*/\1/p' \
  | sed 's/.*\/\(.*\)/\1/' \
  | while read FILE; do
      cp -p "orig/data/$FILE" filtered/data
    done
(
  cd filtered || exit 1
  zip -rX "../$MESSAGES_FILTERED" .
)

rm -rf orig
rm -rf filtered