| 1 | #!/usr/bin/env bash |
| 2 | # installsystemdservice.sh — Installs filemanager as a systemd service. |
| 3 | # Must be run as root: sudo ./installsystemdservice.sh |
| 4 | |
| 5 | set -euo pipefail |
| 6 | |
| 7 | if [[ "$(id -u)" -ne 0 ]]; then |
| 8 | echo "Error: this script must be run as root (use sudo)." >&2 |
| 9 | exit 1 |
| 10 | fi |
| 11 | |
| 12 | SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" |
| 13 | SERVICE_NAME="filemanager" |
| 14 | SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service" |
| 15 | |
| 16 | # Resolve the user who owns the project directory (i.e. the user who cloned it, |
| 17 | # not root). Falls back to the SUDO_USER env var, then 'pi'. |
| 18 | RUN_AS="${SUDO_USER:-pi}" |
| 19 | |
| 20 | echo "[install] Project directory : $SCRIPT_DIR" |
| 21 | echo "[install] Service will run as user: $RUN_AS" |
| 22 | |
| 23 | # Make sure start.sh is executable |
| 24 | chmod +x "$SCRIPT_DIR/start.sh" |
| 25 | |
| 26 | cat > "$SERVICE_FILE" <<EOF |
| 27 | [Unit] |
| 28 | Description=File Manager |
| 29 | After=network.target |
| 30 | |
| 31 | [Service] |
| 32 | Type=simple |
| 33 | User=${RUN_AS} |
| 34 | WorkingDirectory=${SCRIPT_DIR} |
| 35 | ExecStart=${SCRIPT_DIR}/start.sh |
| 36 | Restart=always |
| 37 | RestartSec=5 |
| 38 | # Allow binding to privileged ports (< 1024) without running as root. |
| 39 | AmbientCapabilities=CAP_NET_BIND_SERVICE |
| 40 | CapabilityBoundingSet=CAP_NET_BIND_SERVICE |
| 41 | |
| 42 | [Install] |
| 43 | WantedBy=multi-user.target |
| 44 | EOF |
| 45 | |
| 46 | echo "[install] Service file written to $SERVICE_FILE" |
| 47 | |
| 48 | systemctl daemon-reload |
| 49 | systemctl enable "${SERVICE_NAME}" |
| 50 | systemctl restart "${SERVICE_NAME}" |
| 51 | |
| 52 | echo "[install] Done. Service status:" |
| 53 | systemctl status "${SERVICE_NAME}" --no-pager |