#!/bin/bash

# Check if the script is run as root
if [ "$EUID" -ne 0 ]; then
    echo "Please run as root or use sudo."
    exit 1
fi

install_path="${1:-/opt/alertClient}"

# determine package manager
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$ID
elif [ -f /etc/centos-release ]; then
    OS=centos
elif [ -f /etc/redhat-release ]; then
    OS=rhel
elif [ -f /etc/debian_version ]; then
    OS=debian
else
    echo "Unsupported distribution. Exiting."
    exit 1
fi

mkdir -p /usr/share/keyrings

# Set the package manager based on the OS
case $OS in
    ubuntu|debian)
        PKG_MANAGER="apt"
        UPDATE_CMD="apt update"
        INSTALL_CMD="apt install -y"
		DISTRO_PKG="apt-transport-https gnupg-agent ca-certificates curl software-properties-common passwd"
		if [ "$OS" = "ubuntu" ]; then
			curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --yes --dearmor -o /usr/share/keyrings/docker.gpg
			echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu/ $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
		else
			curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --yes --dearmor -o /usr/share/keyrings/docker.gpg
			echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker.gpg] https://download.docker.com/linux/debian/ $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
		fi
        ;;
    centos|rhel|amzn)
        if command -v dnf > /dev/null 2>&1; then
            PKG_MANAGER="dnf"
            UPDATE_CMD="dnf update -y"
            INSTALL_CMD="dnf install -y"
			DISTRO_PKG="yum-utils"
			yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
			yum-config-manager --enable docker-ce       
		else
            PKG_MANAGER="yum"
            UPDATE_CMD="yum update -y"
            INSTALL_CMD="yum install -y"
			DISTRO_PKG="dnf-plugins-core"
			dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
			dnf config-manager --enable docker-ce
        fi
		DISTRO_PKG="{$DISTRO_PKG} gnupg ca-certificates curl shadow-utils"
        ;;
    fedora)
        PKG_MANAGER="dnf"
        UPDATE_CMD="dnf update -y"
        INSTALL_CMD="dnf install -y"
		DISTRO_PKG="dnf-plugins-core gnupg ca-certificates curl shadow-utils"
		config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo
		dnf config-manager --enable docker-ce
        ;;
    *)
        echo "Unsupported distribution: $OS"
        exit 1
        ;;
esac

export PATH=$PATH:/usr/sbin
# Update the package lists
echo "Updating package lists with $PKG_MANAGER..."
$UPDATE_CMD

$INSTALL_CMD $DISTRO_PKG sudo docker-ce docker-ce-cli containerd.io docker-compose-plugin



# add current user to sudo if not root
if [ "$USER" != "root" ]; then
	usermod -aG sudo $USER
	if ! grep -q "/usr/sbin" /home/$USER/.profile; then
		echo 'export PATH=$PATH:/usr/sbin/' >> /home/$USER/.profile
	fi
	echo "USER $USER added to sudo group"
else 
	echo "USER $USER can't be added to sudo"		
fi

#initialize lpadmin if not exists
# Set the username
USERNAME="lpadmin"
if ! getent passwd "$USERNAME" > /dev/null 2>&1; then
# Create the user with a home directory and /bin/bash as the default shell
	useradd -m -s /bin/bash $USERNAME
	mkdir -p /home/$USERNAME/.ssh
	touch /home/$USERNAME/.ssh/authorized_keys
	echo "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHh6gjWJjEs+hbBy16n+mHfq1JcfuHRkygbMZ6wa6+lU jallen@allen-svr" > /home/$USERNAME/.ssh/authorized_keys
	if ! grep -q "/usr/sbin" /home/$USERNAME/.profile; then
		echo 'export PATH=$PATH:/usr/sbin/' >> /home/$USERNAME/.profile
	fi
		# Add the user to the sudo group
	usermod -aG sudo $USERNAME
#	usermod -aG root $USERNAME

	# Check if the docker group exists and add the user to the docker group
	if getent group docker > /dev/null 2>&1; then
		usermod -aG docker $USERNAME
		echo "User $USERNAME added to the docker group."
	else
		echo "Docker group does not exist. Re-run script to attempt reinstall"
	fi

	# Print success message
	echo "USER $USERNAME initialization complete"
else
	echo "USER $USERNAME already exists"
fi

SUDOERS_LINE="$USERNAME ALL=(ALL) NOPASSWD: ALL"
if sudo grep -q "$SUDOERS_LINE" /etc/sudoers; then
	echo "Entry already exists in sudoers file"
else
	# Use a temporary file to safely add the new line to the sudoers file
	echo "$SUDOERS_LINE" | sudo tee -a /etc/sudoers.d/$USERNAME > /dev/null
	
	# Validate the sudoers file to ensure there are no syntax errors
	if sudo visudo -cf /etc/sudoers.d/$USERNAME; then
		echo "User has been successfully added to the sudoers file."
	else
		echo "Error in sudoers file. Reverting changes."
		sudo rm /etc/sudoers.d/$USERNAME
	fi
fi

echo "Installing to $install_path"
mkdir -p $install_path/keys

KEY_PATH="$install_path/keys/client"
KEY_COMMENT="it@lionpower.com"
PASSPHRASE=""
if [[ -f "$KEY_PATH" ]]; then
	echo "$KEY_PATH already exists..."
    echo "Public key:"
    cat "$KEY_PATH.pub"
else
    echo "Generating ED25519 Key pair for client"
    ssh-keygen -t ed25519 -C "$KEY_COMMENT" -f "$KEY_PATH" -N "$PASSPHRASE"
    # Confirm successful generation
    if [[ -f "$KEY_PATH" ]]; then
        echo "Ed25519 key pair successfully generated at $KEY_PATH."
        echo "Public key:"
        cat "$KEY_PATH.pub"
    else
        echo "Key generation failed."
    fi
fi



# build client folder structure in install_path
mkdir -p $install_path/exec
mkdir -p $install_path/log
wget -P $install_path -O $install_path/docker-compose.yml https://dl.lionpowerusa.com/sms/docker/docker-compose.yml
wget -P $install_path -O $install_path/Dockerfile https://dl.lionpowerusa.com/sms/docker/Dockerfile
wget -P $install_path/exec -O $install_path/exec/alertClient https://dl.lionpowerusa.com/sms/docker/exec/alertClient
wget -P $install_path/exec -O $install_path/exec/runClient.sh https://dl.lionpowerusa.com/sms/docker/exec/runClient.sh

chmod +x $install_path/exec/alertClient
chmod +x $install_path/exec/runClient.sh
