#!/bin/sh
# File: generate-zips-from-sword-dir.sh
# Location: server3:/mnt/mirror/sword
# Author: bgstack15
# Startdate: 2024-06-06-5 17:21
# SPDX-License-Identifier: GPL-3.0-only
# Title: Generate Zips from Existing .Sword Dir
# Purpose: convert a .sword dir back into modules for loading into my sword library
# History:
# Usage: Use when I am converting an existing .sword dir to set of modules for the repo.
# Reference:
#    https://serverfault.com/questions/108024/silent-7za-compression/827833#827833
# Improve:
# Dependencies:
#    7za
# Documentation: /mnt/public/Support/Programs/BibleTimeMini/sword-repo-readme.md

SWORD_DIR="${SWORD_DIR:-$( dirname $( readlink -f "${0}" ) )}"
OUTDIR="${OUTDIR:-${SWORD_DIR}}"

cd "${SWORD_DIR}"
{ test ! -d mods.d || test ! -d modules ; } && {
   echo "Error: this is not a sword directory. Aborted." 1>&2
   exit 1
}
for mod in mods.d/*.conf ;
do
   mod_name="$( grep -h -E '^\s*\[' "${mod}" | head -n1 | tr -d '[]\r' )"
   datapath="$( awk -F'=' '$1~/DataPath/{print $2}' "${mod}" | sed -r -e 's@^\.\/@@;' )"
    # OpenHymnal has an incorrect DataPath so drilling up solves that.
   _x=0
   _max=4
   while { ! test -e "${datapath}" && test $_x -lt $_max ; } ; do datapath="$( dirname "${datapath}" )" ; echo "For ${mod}, checking ${datapath}" 1>&2 ; _x=$((_x+1)) ; done ;
   #test $_x -ge $_max && { echo "Cannot build ${mod_name}.zip because datapath is broken. Skipping..." 1>&2 ; continue ;}
   echo "${mod_name}.zip" "${mod}" "${datapath}"
   7za -bsp0 -bso0 a "${OUTDIR%%/}/${mod_name}.zip" "${mod}" "${datapath}"
done
