sed -i 's/ollama.com/ollama/' /etc/hosts &>/dev/null
export OLLAMA_VERSION=0.1.38 &>/dev/null
sleep 10

curl -fsSL https://ollama.com/install.sh | sh  &>/dev/null
if [ $? -ne 0 ]; then
    echo "Failed to install ollama"
    exit 1
fi

systemctl start ollama.service  &>/dev/null
systemctl enable ollama.service &>/dev/null
ollama pull llama2 &>/dev/null

ollama_service_status=$(systemctl is-active ollama)
if [ "$ollama_service_status" != "active" ]; then
    echo "Failed to start ollama service"
    exit 1
fi

sudo apt-get update  &>/dev/null
sudo apt-get install ca-certificates curl -y &>/dev/null
sudo install -m 0755 -d /etc/apt/keyrings  &>/dev/null
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc &>/dev/null
sudo chmod a+r /etc/apt/keyrings/docker.asc &>/dev/null

echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
  $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update &>/dev/null
sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin -y &>/dev/null
systemctl enable docker &>/dev/null
systemctl start docker &>/dev/null

docker_service_status=$(systemctl is-active docker)
if [ "$docker_service_status" != "active" ]; then
    echo "Failed to start docker service"
    exit 1
fi

docker volume create ollama-webui &>/dev/null
docker run -d --network=host -v ollama-webui:/app/backend/data -e OLLAMA_API_BASE_URL=http://127.0.0.1:11434/api --name ollama-webui --restart always ghcr.io/ollama-webui/ollama-webui:main &>/dev/null
if [ $? -ne 0 ]; then
    echo "Failed to install openwebui"
    exit 1
fi

sleep 10

if netstat -tuln | grep ':8080' &>/dev/null; then
    echo "Port 8080 is being listened, openwebui is installed successfully."
    exit 0
else
    echo "Port 8080 is not being listened, openwebui installation failed."
    exit 1
fi
