#!/bin/sh
#
#	Copyright 2026 (c) Shin-ichi Nagamura.
#	All rights reserved.
#
#	$Id$
#
# periodicex USERNAME DIRNAME

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin

USERNAME=$1
SECTION=$2
LOCKFILE="/var/run/periodic.$SECTION.lock"
TARGET_DIR="/usr/local/etc/periodic/$SECTION"

if [ ! -d "$TARGET_DIR" ]; then
    echo "Directory not found: $TARGET_DIR" >&2
    exit 1
fi

flock -n "$LOCKFILE" su "$USERNAME" -c "
    for full_path in \$(find \"$TARGET_DIR\" -maxdepth 1 -type f -executable | sort); do
        echo \"===> Executing \$full_path as $USERNAME\"
        \"\$full_path\"
    done
"
