#!/bin/sh

# Check if service management is available by testing gitlab-runner status.
# This will fail if neither systemctl nor service commands are available.
check_service_management() {
  set +e
  error_output=$(gitlab-runner status 2>&1)
  status_exit_code=$?
  set -e

  # Check the error message to see if it's a service management issue
  if [ $status_exit_code -eq 0 ]; then
    # Command succeeded
    return 0
  fi

  if echo "$error_output" | grep -q "executable file not found"; then
    return 1
  fi

  # If status command works but returns non-zero (e.g., service not installed yet), that's fine
  return 0
}

if ! check_service_management; then
  echo "GitLab Runner: Service management is not available on this system."
  echo "GitLab Runner: Skipping service stop/uninstall commands."
  exit 0
fi

gitlab-runner stop >/dev/null 2>/dev/null
gitlab-runner uninstall >/dev/null 2>/dev/null
exit 0
