#!/bin/bash
dockerName=steamcmd

function installPalworld(){
	if ! installDocker; then
		echo "install docker falied"
		return 1
	fi
	containerId=$(docker ps -aqf name=$dockerName)
	echo "$containerId"
	if [ -n "$containerId" ]; then
		echo "docker container $containerId exists, will delete and reinstall"
		docker stop "$containerId"
		docker rm "$containerId"
	fi

	while true; do
    	if ! docker run -dit -p 8211:8211 --name $dockerName --net host  cm2network/steamcmd; then
			echo "steamcmd install failed, retry after 5s"
			sleep 5s
		fi
		echo "steamcmd install success"
		break
	done
	while true; do
		if docker exec -i $dockerName bash -c "/home/steam/steamcmd/steamcmd.sh +login anonymous +app\_update 2394010 validate +quit";then
			echo "install palworld success"
			break
		fi
		echo "palworld install failed, sleep 5s retry"
		sleep 5s
	done

	if ! docker exec -dit $dockerName  bash -c "/home/steam/Steam/steamapps/common/PalServer/PalServer.sh"; then
		echo "start palworld failed"
	else
		echo "succeed to start palworld"
		echo "good game!"
	fi
	return 0
}

function installDocker(){
	if cat /etc/redhat-release; then
		echo "CentOS"
		if ! installDockerCentos;then
			echo "install docker falied"
			return 1
		fi
		return 0
	elif cat /etc/lsb-release; then
		echo "Ubuntu"	
		 if ! installDockerUbuntu; then
			echo "install docker falied"
			return 1
		fi
		return 0
	else
		echo "only support centos or ubuntu"
		return 1
	fi
}

# install docker env
function installDockerCentos(){
    if docker -v; then
        echo "docker has installed, skip"
	    return 0
    fi

    echo "[docker] docker env not found, will install it after"
    echo "[docker] installing docker env ..."

    yum install epel-release -y
    yum clean all

    sudo yum install -y yum-utils device-mapper-persistent-data lvm2
    sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    sudo yum install -y docker-ce
    systemctl enable docker
    systemctl start docker

    if ! docker -v; then
        echo "[docker] docker install failed, exit"
        return 1
    fi
    echo "[docker] finish to install docker env"
    return 0
}

function installDockerUbuntu() {
	if docker -v; then
        echo "docker has installed, skip"
	    return 0
    fi
	echo "[docker] docker env not found, will install it after"
    echo "[docker] installing docker env ..."
   	apt-get -y install apt-transport-https ca-certificates curl software-properties-common
	curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | sudo apt-key add -
	sudo add-apt-repository -y "deb [arch=amd64] https://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable"
	apt-get -y update
	apt-get -y install docker-ce
	systemctl enable docker
    systemctl start docker
	if ! docker -v; then
        echo "[docker] docker install failed, exit"
        return 1
    fi
    echo "[docker] finish to install docker env"
    return 0
	
}

installPalworld
