#!/bin/bash

if [ "$EUID" -ne 0 ]
  then echo "Please run as root"
  exit
fi

get_distribution() {
	lsb_dist=""
	if [ -r /etc/os-release ]; then
		lsb_dist="$(. /etc/os-release && echo "$ID")"
	fi
	echo "$lsb_dist"
}

docker_registry_url='registry.dsign.host'
dsign_repo_url='repo.dsign.host'

docker_login() {
  docker login --username=$provider --password=$entered_password $docker_registry_url
  if [ $? -eq 0 ]; then
    echo "Docker login succeeded."
  else
    echo "Docker login failed. Exiting. Contact your dsign provider."
    exit 1
  fi
}

pull_docker_compose(){
  mkdir container
  cd container
  url="https://$provider:$entered_password@$dsign_repo_url/$provider/docker-compose.yml"
  wget "$url" -P "."
  if [ $? -eq 0 ]; then
    echo "docker-compose is in container directory. Edit it to match your setup."
    echo "afterwards, in the directory 'container' run the command docker-compose up --build"
  else
    echo "Pulling the docker-compose image failed. Exiting. Contact your dsign provider."
    exit 1
  fi

}

#install docker
function install_docker {
  echo "Installing docker"
  distribution=$(get_distribution)
  if [ "$distribution" == "rocky" ]; then
    echo "The distribution is Rocky Linux."
    curl -fsSL https://get.docker.com | sed 's/echo "$lsb_dist"/echo "centos"/g' | bash 
  else
    curl -fsSL https://get.docker.com | bash 
  fi
}

#Check if docker is installed

if [[ $(which docker) && $(docker --version) ]]; then
    echo "Docker is installed."
  else
  while true; do  # Ask the user if they want to install Docker
    read -p "Do you want to install Docker now? (yes/no): " choice

    if [[ "$choice" =~ ^[Yy][Ee][Ss]|[Yy]$ ]]; then
      install_docker
      break
    elif [[ "$choice" =~ ^[Nn][Oo]$ ]]; then
      echo "Exiting without installing Docker."
      exit 0
    else
      echo "Invalid response. Please enter 'yes' or 'no'."
    fi
  done
fi

echo "Settings up docker registry"

PS3="Choose your company: "
options=("Cikom" "DevTest" "Quit")
url='https://repo.dsign.host'

select choice in "${options[@]}"; do
    case "$choice" in
        "Cikom")
            provider="cikom"
            break
            ;;
        "DevTest")
            provider="test"
            break
            ;;
        "Quit")
            echo "Exiting..."
            exit 0
            ;;
        *) echo "Invalid choice";;
    esac
done


while true; do
    # Ask for a password
    read -s -p "Enter your password: " entered_password
    # Make an HTTP request to the website with the entered password
    response=$(curl --write-out %{http_code} -s -u "$provider:$entered_password" --output /dev/null -I "$url/$provider/")
    # Check the response status code
    if [[ "$response" =~ ^2[0-9][0-9] ]]; then
        echo "Password is correct."
        break
    else
        echo "Password is incorrect. Try again."
    fi
done

docker_login
pull_docker_compose
