Created
January 18, 2024 19:31
-
-
Save alancnet/3de669842ea5d5b9f953beae099d96d6 to your computer and use it in GitHub Desktop.
Self installing service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -e | |
SERVICE_NAME="self-installing-service" | |
SERVICE_DESCRIPTION="A self installing service bash script" | |
SELF_FILE=$(readlink -f $0) | |
SELF_DIR=$(dirname $SELF_FILE) | |
SELF_FILENAME=$(basename $SELF_FILE) | |
SERVICE_CONFIG="/etc/systemd/system/${SERVICE_NAME}.service" | |
SERVICE_FILENAME=$(basename $SERVICE_CONFIG) | |
function daemon () { | |
while true; do | |
echo "I am a service..." | |
sleep 5 | |
done | |
} | |
function install () { | |
echo "Installing ${SERVICE_NAME}..." | |
cat <<EOL | sudo tee $SERVICE_CONFIG > /dev/null | |
[Unit] | |
Description=${SERVICE_DESCRIPTION} | |
After=network.target | |
[Service] | |
ExecStart=${SELF_FILE} daemon | |
WorkingDirectory=${SELF_DIR} | |
User=${USER} | |
Restart=always | |
KillSignal=SIGINT | |
SyslogIdentifier=${SERVICE_NAME} | |
[Install] | |
WantedBy=multi-user.target | |
EOL | |
sudo systemctl daemon-reload | |
sudo systemctl enable $SERVICE_FILENAME | |
start | |
} | |
function start () { | |
echo "Starting ${SERVICE_NAME}..." | |
sudo systemctl start $SERVICE_FILENAME | |
} | |
function restart () { | |
echo "Restarting ${SERVICE_NAME}..." | |
sudo systemctl restart $SERVICE_FILENAME | |
} | |
function stop () { | |
echo "Stopping ${SERVICE_NAME}..." | |
sudo systemctl stop $SERVICE_FILENAME | |
} | |
function uninstall () { | |
echo "Uninstalling ${SERVICE_NAME}..." | |
sudo systemctl stop $SERVICE_FILENAME | |
sudo systemctl disable $SERVICE_FILENAME | |
sudo rm $SERVICE_CONFIG | |
sudo systemctl daemon-reload | |
} | |
function logs () { | |
journalctl -u $SERVICE_FILENAME $1 | |
} | |
function usage () { | |
echo "Usage: $SELF_FILENAME {install|start|restart|stop|uninstall|logs [-f]}" | |
} | |
action=$1 | |
case $action in | |
daemon) | |
daemon | |
;; | |
install) | |
install | |
;; | |
start) | |
start | |
;; | |
restart) | |
restart | |
;; | |
stop) | |
stop | |
;; | |
uninstall) | |
uninstall | |
;; | |
logs) | |
logs $2 | |
;; | |
*) | |
echo "Usage: $SELF_FILENAME {install|start|restart|stop|uninstall|logs [-f]}" | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment