#!/bin/sh
# Custom Agent Installer for stuff.furrr.kr

NZ_MIRROR_URL="https://stuff.furrr.kr/nz"
NZ_AGENT_PATH="/opt/nezha/agent"
NZ_AGENT_SERVICE="/etc/systemd/system/nezha-agent.service"

red='\033[0;31m'; green='\033[0;32m'; plain='\033[0m'
err() { printf "${red}%s${plain}\n" "$*" >&2; exit 1; }
info() { printf "${green}%s${plain}\n" "$*"; }

HOST=$1; PORT=$2; SECRET=$3; TLS=$4

if [ -z "$HOST" ] || [ -z "$PORT" ] || [ -z "$SECRET" ]; then
    err "Usage: ./install_agent.sh <host> <port> <secret>"
fi

uname_m=$(uname -m)
case "$uname_m" in
    x86_64|amd64) ARCH="amd64" ;;
    aarch64|arm64) ARCH="arm64" ;;
    s390x) ARCH="s390x" ;;
    riscv64) ARCH="riscv64" ;;
    *) err "Unknown Architecture: $uname_m" ;;
esac

info "Downloading Agent (${ARCH}) from mirror..."

mkdir -p "$NZ_AGENT_PATH"
rm -f "$NZ_AGENT_PATH/agent.zip"
rm -f "$NZ_AGENT_PATH/nezha-agent"

# Download using the DASHED name we created on the server
curl -L -f -o "$NZ_AGENT_PATH/agent.zip" "${NZ_MIRROR_URL}/nezha-agent-linux-${ARCH}.zip"

if [ ! -s "$NZ_AGENT_PATH/agent.zip" ]; then
    err "Download failed. File empty or missing on mirror."
fi

# Unzip
unzip -q -o "$NZ_AGENT_PATH/agent.zip" -d "$NZ_AGENT_PATH" || err "Unzip failed."

# Handle the fact that v0.20.5 zip might contain a folder or file with underscores
# We find the binary regardless of what it's named inside
BIN_PATH=$(find "$NZ_AGENT_PATH" -type f -name "nezha-agent" | head -n 1)
if [ -z "$BIN_PATH" ]; then
    # Try finding it if it has an extension or different name
    BIN_PATH=$(find "$NZ_AGENT_PATH" -type f -name "nezha-agent*" ! -name "*.zip" | head -n 1)
fi

if [ -z "$BIN_PATH" ]; then
    err "Could not find nezha-agent binary inside the zip."
fi

# Move it to standard location
mv -f "$BIN_PATH" "$NZ_AGENT_PATH/nezha-agent"
chmod +x "$NZ_AGENT_PATH/nezha-agent"
rm -f "$NZ_AGENT_PATH/agent.zip"

# Clean up any leftover folders from unzip
find "$NZ_AGENT_PATH" -mindepth 1 -type d -exec rm -rf {} +

# Create Service with CORRECT FLAGS
FLAGS="--disable-auto-update --disable-force-update --disable-command-execute"
if [ "$TLS" = "y" ] || [ "$TLS" = "true" ]; then
    FLAGS="$FLAGS --tls"
fi

cat <<SERVICE > "$NZ_AGENT_SERVICE"
[Unit]
Description=Nezha Agent
After=network.target
[Service]
Type=simple
User=root
WorkingDirectory=$NZ_AGENT_PATH
ExecStart=$NZ_AGENT_PATH/nezha-agent "-s" "$HOST:$PORT" "-p" "$SECRET" $FLAGS
Restart=always
[Install]
WantedBy=multi-user.target
SERVICE

systemctl daemon-reload
systemctl enable nezha-agent
systemctl restart nezha-agent
info "Agent Installed & Started."
