#!/bin/bash

type=$1
filename=$2

if [ -z "$type" ] || [ -z "$filename" ]; then
    echo "Usage: $0 <type> <filename>"
    exit 1
fi

dirpath=$(dirname "$filename")
echo $type $filename $dirpath

network_dest_dir="/home/forlinx/Desktop/workspace/TPMFM-A"
monitor_dest_dir="/home/forlinx/monitor"
compute_dest_dir="/home/forlinx/Desktop/workspace/dataParsing"

mkdir -p "$network_dest_dir" "$monitor_dest_dir" "$compute_dest_dir"

echo "stopping app..."
systemctl stop monitor
echo "Waiting for monitor to fully stop..."
sleep 2  # 等待 2 秒
while systemctl is-active --quiet monitor; do
    echo "monitor still running, waiting..."
    sleep 1
done
echo "monitor stopped."

# 根据类型解压
case "$type" in
    network)
        echo "Extracting network package..."
        tar --overwrite -zxvf "$filename" -C "$network_dest_dir"
        ;;
    monitor)
        echo "Extracting monitor package..."
        tar --overwrite -zxvf "$filename" -C "$monitor_dest_dir"
        if [ -f $monitor_dest_dir/monitor.service ]; then
            cp "$monitor_dest_dir/monitor.service" /etc/systemd/system/
            systemctl daemon-reload
        else
            echo "monitor.service not found in $monitor_dest_dir"
        fi
        ;;
    compute)
        echo "Extracting compute package..."
        tar --overwrite -zxvf "$filename" -C "$compute_dest_dir"
        ;;
    *)
        echo "Unsupported file type: $type"
        exit 1
        ;;
esac

echo "restarting app..."
systemctl enable --now monitor


echo "begin cleanup..."
if [ -d "$dirpath" ]; then
    rm -rf "$dirpath"/*
else
    echo "Directory $dirpath does not exist, skipping cleanup."
fi
echo "cleanup complete"

# 再次检查 monitor 服务状态
status=$(systemctl is-active monitor)
echo "Monitor service status after restart: $status"


sleep 3
# 可选：显示详细状态
# systemctl status monitor
journalctl -u monitor.service -n 100


echo ""
echo "脚本执行完成！"