#!/usr/bin/env bash set -euo pipefail APPFACTORY_ROOT="/opt/appfactory" DB_FILE="$APPFACTORY_ROOT/data/appfactory/appfactory.db" WORKSPACE_DIR="$APPFACTORY_ROOT/workspace" DELETE_SCRIPT="$WORKSPACE_DIR/appfactory-tools/scripts/delete-app.sh" DRY_RUN="${DRY_RUN:-1}" MIN_AGE_HOURS="${MIN_AGE_HOURS:-24}" MIN_AGE_MINUTES=$((MIN_AGE_HOURS * 60)) PROTECTED_WORKSPACES=( appfactory-infrastructure appfactory-monitor appfactory-portal appfactory-tools appfactory-webhook appfactory-worker python-fastapi-template ) log() { printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*" } is_protected() { local candidate="$1" local protected for protected in "${PROTECTED_WORKSPACES[@]}"; do if [ "$candidate" = "$protected" ]; then return 0 fi done return 1 } is_registered() { local candidate="$1" sqlite3 "$DB_FILE" \ "SELECT 1 FROM apps WHERE id = '$candidate' LIMIT 1;" | grep -qx 1 } if [ ! -f "$DB_FILE" ]; then log "ERROR: Databáze neexistuje: $DB_FILE" exit 1 fi if [ ! -x "$DELETE_SCRIPT" ]; then log "ERROR: Mazací skript není spustitelný: $DELETE_SCRIPT" exit 1 fi found=0 deleted=0 failed=0 while IFS= read -r app_dir; do app_id="$(basename "$app_dir")" if is_protected "$app_id"; then continue fi if is_registered "$app_id"; then continue fi if ! find "$app_dir" -maxdepth 0 -mmin "+$MIN_AGE_MINUTES" | grep -q .; then log "SKIP fresh orphan candidate: $app_id" continue fi found=$((found + 1)) log "ORPHAN: $app_id" if [ "$DRY_RUN" = "1" ]; then log "DRY-RUN: spustil by se delete-app.sh $app_id" continue fi if "$DELETE_SCRIPT" "$app_id"; then deleted=$((deleted + 1)) log "DELETED: $app_id" else failed=$((failed + 1)) log "FAILED: $app_id" fi done < <( find "$WORKSPACE_DIR" \ -mindepth 1 \ -maxdepth 1 \ -type d \ -print | sort ) log "Finished. Found=$found Deleted=$deleted Failed=$failed DryRun=$DRY_RUN" if [ "$failed" -gt 0 ]; then exit 1 fi