#!/bin/bash
# Copyright 2026 ANNE Media - https://anne.media
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# sign.sh -- detached-sign AM·OS packages with the release key.
#
# Signatures are ASCII-armored and land next to each package as
# <pkg>.txz.asc. The .asc mtime is set to match the package's, so
# freshness-based tools (slackpkg) see a consistent pair.
#
# Every package is re-signed on every run. There is no "already
# signed, skip" shortcut: a stale .asc left next to a repackaged
# .txz by cp -a (which preserves mtimes) is exactly the failure
# mode this script exists to eliminate, and re-signing is cheap.
#
# Usage:
#   sign.sh [path ...]
#
#   With no arguments, signs every package under $BUILD (the production
#   tree, same default as sync.sh). With arguments, each is treated as
#   either a directory to walk recursively or a package file to sign
#   directly.
#
# Environment:
#   BUILD      production tree       (default: /root/amos-current/repo)
#   GPG_KEY    signing key user-id   (default: radanne@anne.media)

set -eu
BUILD_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
BUILD="$(cd -- "$BUILD_DIR/../amos64" && pwd -P)"
GPG_KEY="${GPG_KEY:-radanne@anne.media}"

die() { echo "ERROR: $*" >&2; exit 1; }
log() { echo ">>> $*"; }

[ -n "$GPG_KEY" ] || die "GPG_KEY is empty; nothing to sign with"

gpg --list-secret-keys "$GPG_KEY" >/dev/null 2>&1 \
  || die "no secret key for '$GPG_KEY' in keyring"

# Sign one package. Always re-signs; the previous .asc is removed
# first so a failed gpg run cannot leave a stale signature in place.
# Return codes:
#   0  signed
#   1  signing failed
sign_one() {
    local txz="$1"
    [ -f "$txz" ] || return 0

    case "$txz" in
        *.t[gx]z) ;;
        *) return 0 ;;
    esac

    local asc="${txz}.asc"
    rm -f "$asc"
    if ! gpg --pinentry-mode loopback --detach-sign --armor --yes \
             --local-user "$GPG_KEY" \
             --output "$asc" "$txz"; then
        return 1
    fi
    touch -r "$txz" "$asc"
    return 0
}

sign_tree() {
    local root="$1"
    local signed=0 failed=0 txz rc rel

    while IFS= read -r -d '' txz; do
        rel="${txz#$root/}"
        rc=0
        sign_one "$txz" || rc=$?
        case "$rc" in
            0) printf '  + %s\n' "$rel"
               signed=$((signed + 1)) ;;
            *) printf '  ! %s\n' "$rel" >&2
               failed=$((failed + 1)) ;;
        esac
    done < <(find "$root" -type f \( -name '*.txz' -o -name '*.tgz' \) -print0)

    log "  ${root}: $signed signed, $failed failed"
    [ "$failed" -eq 0 ]
}

if [ "$#" -eq 0 ]; then
    [ -d "$BUILD" ] || die "BUILD dir not found: $BUILD"
    log "Signing packages under $BUILD with $GPG_KEY"
    sign_tree "$BUILD"
else
    log "Signing explicit paths with $GPG_KEY"
    rc=0
    for arg in "$@"; do
        if [ -d "$arg" ]; then
            sign_tree "$arg" || rc=1
        elif [ -f "$arg" ]; then
            r=0
            sign_one "$arg" || r=$?
            case "$r" in
                0) log "  + $(basename "$arg")" ;;
                *) echo "!!! signing failed: $arg" >&2; rc=1 ;;
            esac
        else
            echo "!!! not a file or directory: $arg" >&2
            rc=1
        fi
    done
    exit "$rc"
fi