#!/usr/bin/env bash
# =============================================================================
# promote-all.sh  —  lives IN the web bin dir on Henry
#                    (/var/www/cloudcoinconsortium.com/bin/).
#
# Refreshes the CANONICAL desktop download names from the newest dated build of
# each platform, so both the bytes AND the date shown in the nginx autoindex
# ("Index of /bin/") always track the latest release:
#
#     QMail.dmg       <-  newest  qmail-mac-YYYY-MM-DD.dmg
#     QMail.exe       <-  newest  qmail-windows-YYYY-MM-DD.exe
#     QMail.AppImage  <-  newest  qmail-linux-desktop-YYYY-MM-DD.AppImage
#
# Then regenerates SHA256SUMS (only if something actually changed).
#
# WHY the autoindex shows "old" dates: it prints each file's true mtime. The
# QMail.* names are plain copies; if they aren't refreshed when a newer dated
# build lands, they keep their old bytes AND old date. This script fixes that.
# It uses `install` (NOT cp -p), so a promoted file gets a fresh mtime = now.
#
# It also ARCHIVES superseded builds: for each platform family it keeps only the
# newest dated file at the top level and moves older dated files into
# archive/<YYYY-MM-DD>/, so the browsable "Index of /bin/" shows just the current
# release of each executable. Older builds are never lost — they already exist as
# identical copies under archive/ (a move that finds an identical archived copy
# simply drops the top-level duplicate; otherwise the file is moved into place).
# The  *-latest.*  aliases and canonical QMail.* names are never touched.
#
#   Run in a Terminal on Henry (web dir is root-owned -> sudo):
#       sudo /var/www/cloudcoinconsortium.com/bin/promote-all.sh
#
# This supersedes promote-mac-latest.sh (which did macOS only).
# The download pages point at these canonical names:
#   - cloudcoinconsortium.com/use.php        -> bin/QMail.dmg
#   - distributedmailsystem.com /download    -> bin/QMail.{exe,dmg,AppImage}
# After running, update those pages' hard-coded SHA256s if they list any
# (see deploy/dms-downloads-mac-checksum.md).
# =============================================================================
set -euo pipefail

BIN_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$BIN_DIR"

changed=0

# newest file matching a date-anchored glob (ignores the *-latest.* names)
newest() {
  local f best=""
  for f in $1; do
    [[ -e "$f" ]] || continue          # unmatched glob stays literal -> skip
    [[ "$f" > "$best" ]] && best="$f"   # lexical max == newest ISO date
  done
  printf '%s' "$best"
}

promote() {
  local canon="$1" glob="$2" src
  src=$(newest "$glob")
  if [[ -z "$src" ]]; then
    echo "  [$canon] SKIP — no source matching '$glob'"
    return 0
  fi
  if [[ -f "$canon" ]] && cmp -s "$src" "$canon"; then
    echo "  [$canon] already current (= $src)"
    return 0
  fi
  install -m 0644 "$src" ".$canon.tmp"   # install sets mtime = now (no -p)
  mv -f ".$canon.tmp" "$canon"
  echo "  [$canon] <- $src   PROMOTED"
  changed=1
}

# Keep only the newest dated build of a family at top level; move older dated
# builds into archive/<date>/. If an identical copy is already archived, just
# drop the top-level duplicate; otherwise move the file into the archive.
archive_superseded() {
  local glob="$1" f newest="" date dest
  local files=()
  for f in $glob; do [[ -e "$f" ]] && files+=("$f"); done
  [[ ${#files[@]} -eq 0 ]] && return 0
  for f in "${files[@]}"; do [[ "$f" > "$newest" ]] && newest="$f"; done  # newest ISO date
  for f in "${files[@]}"; do
    [[ "$f" == "$newest" ]] && continue
    date=$(printf '%s' "$f" | grep -oE '[0-9]{4}-[0-9]{2}-[0-9]{2}' | head -1)
    [[ -z "$date" ]] && continue
    dest="archive/$date"
    if [[ -f "$dest/$f" ]] && cmp -s "$f" "$dest/$f"; then
      rm -f -- "$f";        echo "  [archive] $f  dropped (identical copy in $dest/)"
    else
      mkdir -p "$dest"; mv -f -- "$f" "$dest/"; echo "  [archive] $f  -> $dest/"
    fi
    changed=1
  done
}

echo "Promoting canonical downloads in $BIN_DIR:"
promote "QMail.dmg"      'qmail-mac-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].dmg'
promote "QMail.exe"      'qmail-windows-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].exe'
promote "QMail.AppImage" 'qmail-linux-desktop-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].AppImage'

echo "Archiving superseded dated builds:"
archive_superseded 'core-linux-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'
archive_superseded 'core-windows-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].exe'
archive_superseded 'qmail-android-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].apk'
archive_superseded 'qmail-mac-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].dmg'
archive_superseded 'qmail-windows-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].exe'
archive_superseded 'qmail-linux-desktop-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].AppImage'
archive_superseded 'qmail-linux-desktop-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].deb'
archive_superseded 'qmail-linux-desktop-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].tar.gz'

if [[ "$changed" -eq 1 ]]; then
  echo "Regenerating SHA256SUMS..."
  ls -1 | grep -vE '^(archive|SHA256SUMS|index\.php)$' | xargs sha256sum > SHA256SUMS
  echo "  SHA256SUMS refreshed ($(grep -c . SHA256SUMS) entries)."
else
  echo "Nothing changed; SHA256SUMS left as-is."
fi

echo "Canonical files now:"
for f in QMail.dmg QMail.exe QMail.AppImage; do
  [[ -f "$f" ]] || continue
  printf "  %-15s %12s bytes  %s\n" "$f" "$(stat -c%s "$f")" "$(stat -c%y "$f" | cut -d. -f1)"
  printf "      sha256 %s\n" "$(sha256sum "$f" | cut -d' ' -f1)"
done
