#!/bin/bash

# C-Relay Systemd Service Uninstallation Script
# This script removes the C-Relay systemd service

set -e

# Configuration
INSTALL_DIR="/opt/c-relay"
SERVICE_NAME="c-relay"
SERVICE_FILE="c-relay.service"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}=== C-Relay Systemd Service Uninstallation ===${NC}"

# Check if running as root
if [[ $EUID -ne 0 ]]; then
   echo -e "${RED}Error: This script must be run as root${NC}"
   echo "Usage: sudo ./uninstall-systemd.sh"
   exit 1
fi

# Stop service if running
echo -e "${YELLOW}Stopping service...${NC}"
if systemctl is-active --quiet $SERVICE_NAME; then
    systemctl stop $SERVICE_NAME
    echo -e "${GREEN}Service stopped${NC}"
else
    echo -e "${GREEN}Service was not running${NC}"
fi

# Disable service if enabled
echo -e "${YELLOW}Disabling service...${NC}"
if systemctl is-enabled --quiet $SERVICE_NAME; then
    systemctl disable $SERVICE_NAME
    echo -e "${GREEN}Service disabled${NC}"
else
    echo -e "${GREEN}Service was not enabled${NC}"
fi

# Remove systemd service file
echo -e "${YELLOW}Removing service file...${NC}"
if [ -f "/etc/systemd/system/$SERVICE_FILE" ]; then
    rm /etc/systemd/system/$SERVICE_FILE
    systemctl daemon-reload
    echo -e "${GREEN}Service file removed${NC}"
else
    echo -e "${GREEN}Service file was not found${NC}"
fi

# Ask about removing installation directory
echo
echo -e "${YELLOW}Do you want to remove the installation directory $INSTALL_DIR? (y/N)${NC}"
read -r response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
    echo -e "${YELLOW}Removing installation directory...${NC}"
    rm -rf $INSTALL_DIR
    echo -e "${GREEN}Installation directory removed${NC}"
else
    echo -e "${GREEN}Installation directory preserved${NC}"
fi

# Ask about removing c-relay user
echo
echo -e "${YELLOW}Do you want to remove the c-relay user? (y/N)${NC}"
read -r response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
    echo -e "${YELLOW}Removing c-relay user...${NC}"
    if id "c-relay" &>/dev/null; then
        userdel c-relay
        echo -e "${GREEN}User c-relay removed${NC}"
    else
        echo -e "${GREEN}User c-relay was not found${NC}"
    fi
else
    echo -e "${GREEN}User c-relay preserved${NC}"
fi

echo
echo -e "${GREEN}=== Uninstallation Complete ===${NC}"
echo -e "${GREEN}C-Relay systemd service has been removed${NC}"