#!/bin/bash
# SPDX-FileCopyrightText: 2026 Andreas Itzchak ("Izzy") Rehberg <izzysoft@qumran.org>
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# Gather monthly app stats. To be run after a month has completed (i.e. for the previous month)
# calls appstats.php + removed_apps.sh, and takes care for git handling (pull/add/commit/push)
set -euo pipefail

if [[ "$0" != "${BASH_SOURCE[0]}" ]]; then
  BASEDIR="$(realpath "$(dirname "${BASH_SOURCE[0]}")")" #"
else
  BASEDIR="$(realpath "$(dirname "$(readlink -mn "${0}")")")"
fi

# -------------------------------------------=[ Config ]=---
CANCEL_ON_DIRTY=0                                           # abort the script should the git tree be dirty (with 'git config pull.rebase true', the pull will fail anyway on a dirty tree) and exit with this return code
OUTDIR="$(realpath "$(jq -r '.outdir' appstats_config.json)")" #"# where the files to commit end up
MONTH="$(date --date='-1 month' +%m)"                       # number of the last week (with Sat being its last day)
YEAR="$(date --date='-1 month' +%Y)"                        # year of the last week (with Sat being its last day)
STAMP="${MONTH}/${YEAR}"                                    # month/year
# ------------------------------------------=[ /Config ]=---


# helper to send error messages to STDERR
printerr() { printf "%s\n" "$*" >&2; }


# ----------------
# --    MAIN    --
# ----------------

pushd "${BASEDIR}" >/dev/null

# check for unstaged changes
git stat --porcelain | grep -Eqv '^[MADR] ' &&  {  # unstaged changes exist
  echo
  printerr "Tree is dirty:"
  git stat --porcelain >&2
  [[ $CANCEL_ON_DIRTY -gt 0 ]] && {
    printerr "aborting."
    echo
    exit $CANCEL_ON_DIRTY
  }
  echo
}

# pull in potential changes from upstream
git pull

# generate the stats
php appstats.php
bash removed_apps.sh

# now add and commit the new stats file to the repo – but only if no other files are staged yet (first char is staging area, second char is working area)
git status --porcelain | grep -qE '^[MADR]' && {    # staged changes exist, we don't want to commit them alongside accidentally (locally modified but not yet staged would be '^ M', staged and modified again '^MM')
  printerr "ERROR: There are already staged files in the repo, aborting."
  exit 22
}

cd "${OUTDIR}"
git add .
git commit -q -m "adding monthly app stats for $STAMP"
git push

popd >/dev/null
