#!/sbin/openrc-run

description="Podman Containers Startup Service"

# Default values for configurable variables
DEFAULT_PODMAN="podman"
DEFAULT_CONTAINER_USER="hane"  

# Allow user to override defaults
PODMAN="${PODMAN:-$DEFAULT_PODMAN}"
CONTAINER_USER="${CONTAINER_USER:-$DEFAULT_CONTAINER_USER}"
RESTART_POLICY="unless-stopped"
command="$PODMAN"
command_args="start --all --filter restart-policy=always"
name="podman-containers"
command_background=true
command_user=hane
pidfile="/var/run/${RC_SVCNAME}.pid"
#pidfile="/tmp/xdg/$UID-xdg-runtime-dir/${RC_SVCNAME}.pid"
output_log="/home/${CONTAINER_USER:-$DEFAULT_CONTAINER_USER}/pihanepi/orchestrating/${RC_SVCNAME}.log"
error_log="/home/${CONTAINER_USER:-$DEFAULT_CONTAINER_USER}/pihanepi/orchestrating/${RC_SVCNAME}.err"

#depend() {
  # Ensure containers start after the network is up
  # need net  # Ensures that the network is up before starting the containers
#}

start() {
  ebegin "Starting Podman containers with restart policy"
  "$PODMAN" start --all --filter restart-policy=$RESTART_POLICY
  eend $?
}

stop() {
  ebegin "Stopping Podman containers with restart policy"
  
  CONTAINERS=$("$PODMAN" container ls --filter restart-policy=$RESTART_POLICY -q)
  
  if [ -n "$CONTAINERS" ]; then
    for CONTAINER in $CONTAINERS; do
     "$PODMAN" stop "$CONTAINER"
    done
    eend $?
  else
    return 0
    eend "No containers with restart policy=always are running."
  fi
}
