#!/bin/bash

set -e
set -x

file=$1
exec=$2

if [ -e "$file" ]; then
    echo "删除已存在的服务文件"
    rm -f $file
fi

cp template.service $file

sed -i "s|^WorkingDirectory=.*|WorkingDirectory=$(pwd)|" $file
sed -i "s|^ExecStart=.*|ExecStart=$(pwd)/${exec}|" $file

sed -i "s|StandardOutput=.*|StandardOutput=file:$(pwd)/stdout.log|" $file
sed -i "s|StandardError=.*|StandardError=file:$(pwd)/stderr.log|" $file

if [ -e "/etc/systemd/system/${file}" ]; then
    sudo rm -f /etc/systemd/system/${file}
fi

sudo cp $file /etc/systemd/system/${file}

sudo systemctl daemon-reload

rm -f $file
