#!/bin/sh
# File: generate-sword-repo.sh
# Location: server3:/mnt/mirror/sword
# Author: bgstack15
# Startdate: 2024-06-06-5 14:33
# SPDX-License-Identifier: GPL-3.0-only
# Title: Generate Sword Repo and Web Page
# Purpose: generate mods.tar.gz for sword repo
# History:
#    2024-06-13-5 12:58 count number of modules
# Usage: Manually when I want to update the repo metadata based on modules available.
# Reference:
# Improve:
#    get icons for Bible, book, other?
#    use all headers
# Dependencies:
#    prebuilt manifest.json
#    7za
# Documentation: /mnt/public/Support/Programs/BibleTimeMini/sword-repo-readme.md

REPO_DIR="${REPODIR:-/mnt/mirror/sword}"
MODULES_DIR="${MODULES_DIR:-${REPO_DIR%%/}/modules}"

generate_mods_d_tar_gz() {
   rm -rf "${REPO_DIR:-NOTHINGTODEL}/mods.d/"*
   rmdir "${REPO_DIR:-NOTHINGTODEL}/mods.d"
   cd "${REPO_DIR}"
   for zip in "${MODULES_DIR}"/*zip ;
   do
      7za -bsp0 -bso0 x "${zip}" mods.d
   done
   rm -f "${REPO_DIR:-NOTHINGTODEL}/mods.d.tar.gz"
   tar -zcf mods.d.tar.gz mods.d
}

generate_web() {
   echo "stub"
   {
      echo "<html>"
      echo "<head>"
      echo "<link rel='stylesheet' href='sword.css'>"
      echo '<meta name="viewport" content="width=device-width, initial-scale=1">'
      echo "<title>Example sword library</title>"
      echo "</head>"
      echo "<body>"
      echo "<h1><img src='bgstack15.png' class='headimg'>Example sword library</h1>"
      echo "<h2>Installing this repo</h2>"
      echo "<h3>AndBible</h3>"
      echo 'Paste this link: <a href="https://www.example.com/mirror/sword">https://www.example.com/mirror/sword</a>'
      _used=0
      for mod in "${REPO_DIR%%/}/mods.d/"*.conf ;
      do
         if test "${_used}" = "0" ;
         then
            _count="$( find "${REPO_DIR%%/}/mods.d/"*.conf -print 2>/dev/null | grep -cE . )"
            echo "<h2>Modules (${_count})</h2>"
            _used=1
            echo "<ul>"
         fi
         mod_name="$( grep -h -E '^\s*\[' "${mod}" | head -n1 | tr -d '[]\r' )"
         version="$( <"${mod}" awk -F'=' '$1~/\<Version/{print $2}')"
         license="$( <"${mod}" awk -F'=' '$1~/DistributionLicense/{print $2}')"
         if echo "${license}" | grep -qiE 'Permission to distribute granted to' ;
         then
            # probably not stackrpms, so do not show link.
            echo "<li>${mod_name}</li>"
         else
            echo "<li><a href='modules/${mod_name}.zip'>${mod_name}</a> <span class='smaller'>${version}</span></li>"
         fi
      done
      if test "${_used}" = "1" ;
      then
         echo "</ul>"
      fi
      echo "</body>"
      echo "<footer>"
      printf '%s' "Last generated: " ; TZ=UTC date "+%FT%TZ"
      echo "</footer>"
      echo "</html>"
   } > "${REPO_DIR%%/}/index.html"
}

test -z "${SKIP_TARBALL}" && generate_mods_d_tar_gz
test -z "${SKIP_WEB}" && generate_web
