#!/bin/bash

set +o pipefail

github_step_summary() {
    [ "" == "$GITHUB_STEP_SUMMARY" ] || echo "$1" >> "$GITHUB_STEP_SUMMARY"
}

output() {
    echo "$1"
    github_step_summary "$1"
}

if [ $# != 1 ]; then
    cat <<-EOF
Usage: check_localization <localizable.strings>

Check the localizable.strings file has all keys in base
EOF
    exit 1
fi

# Get localization keys
basefile=CutBox/Localization/en.lproj/Localizable.strings
keys=$(mktemp)
rg -o '^"[^"]*"' "$basefile" > "$keys"
file="$1"
errors=()

# Check file has all basekeys
while IFS= read -r line; do
    if ! rg -q "$line" "$file"; then
        # collect errors
        errors+=("/* Missing in $file: */")
        errors+=("$line = \"TODO\";")
        errors+=("/* English: $(rg -IN "$line" "$basefile") */")
    fi
done < "$keys"

rg -o '^"[^"]*"' "$file" > "$keys"

# Check file has no additional keys
while IFS= read -r line; do
    if ! rg -q "$line" "$basefile"; then
        # collect errors
        errors+=("remove: $line")
    fi
done < "$keys"

if [ ${#errors[@]} -gt 0 ]; then
    output "- [✗] Error in $file"
    github_step_summary "\`\`\`"
    for error in "${errors[@]}"; do
        output "$error"
    done
    github_step_summary "\`\`\`"
    output ""
    exit 1
else
    output "- [✓] $file"
fi

rm "$keys"
