#!/bin/bash

# moovIT GmbH - B. Dimmel
# WebContent Downloader for Helmut4
# Version: 2.0

# Changelog: Dec 5th 2024
# Initial release
# Changed portainer tag :latest to :lts
# Included a check to ensure the script is run with sudo permissions.
# Added validation for the target OS and improved user interaction.

# Check if the script is run with sudo permissions
if [ "$EUID" -ne 0 ]; then
    echo "Please run this script via sudo bash install.sh"
    exit 1
fi


echo -e "\nStarting Docker+Portainer installation ...\n"
sleep 2


. /etc/os-release 2&>1
mkdir -p /etc/docker
echo -e "{\"log-driver\": \"json-file\",\"log-opts\": {\"max-size\": \"10m\",\"max-file\": \"3\"}}" > /etc/docker/daemon.json

if [[ $NAME == *"Debian"* ]]; then
### DEBIAN 9, 10, 11 ###

# Confirm installation on unsupported OS 
    while true; do

    echo -e "You are running this script on an unsupported machine: $NAME. It is recommended to use an Ubuntu Server LTS";
    read -p "Do you want to proceed with the installation on an unsupported Linux distribution? (y/n)" yn

    case $yn in 
        #If input is yes we leave the loop
        [yY] ) echo "Ok, we will continue with installation  ...";
            mkdir -p /etc/helmut4
            file_path="/etc/helmut4/unsupportedOS"
            current_date_time=$(date)
            echo "Installation on unsupported OS - $current_date_time" > "$file_path"
            break;;
        
        #No - abport binary installaton
        [nN] ) 
            echo -e "\nSkipping installation!";
            exit 1;;
        
        #If input is neither y nor n
        * ) echo "Invalid response for question";
        echo -e "\nManual abortion of installation!";
        exit 1;;
    esac
    done

echo -e "\nStarting the Helmut4-Media Downloader installation on OS $NAME version $VERSION ...\n"
sleep 2

#Install sudo commands
apt-get install sudo -y
sudo apt-get update -y
if [ $? != 0 ]; 
then
echo "aptitude is in use by someone else (maybe the system itself) - please retry later - exiting.."
exit 1
fi

sudo apt-get install ca-certificates curl gnupg lsb-release -y
curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get install docker-ce docker-ce-cli containerd.io -y
sudo apt-get install docker-compose -y
sudo apt-get install httpie jq -y

systemctl restart docker.service
echo -e "\nOS installation part finished - switching over to Docker sub-process ...\n"
sleep 10
### /DEBIAN ###

elif [[ $NAME == *"Ubuntu"* ]]; then
### UBUNTU ###

# Check if OS is Ubuntu Server or another distro
    dpkg -l ubuntu-desktop > /dev/null 2>&1
    if [[ $? -eq 0 ]]; then
        LOCATION="desktop or unknown"
        # Confirm installation on unsupported OS 
        while true; do

        echo -e "You are executing this script on a unsupported & suggested Ubuntu Server LTS machine: $NAME";
        read -p "Do you want to proceed with the installation on an unsupported Linux distribution? (y/n)" yn

        case $yn in 
            #If input is yes we leave the loop
            [yY] ) echo "Ok, we will continue with installation  ...";
                mkdir -p /etc/helmut4
                file_path="/etc/helmut4/unsupportedOS"
                current_date_time=$(date)
                echo "Installation on unsupported OS - $current_date_time" > "$file_path"
                break;;
            
            #No - abport binary installaton
            [nN] ) 
                        echo -e "\nSkipping installation!";
                exit 1;;
            
            #If input is neither y nor n
            * ) echo "Invalid response for question";
            echo -e "\nManual abortion of installation!";
            exit 1;;
        esac
        done

    else
        LOCATION="server"
    fi

echo -e "\nStarting the Helmut4-Media Downloader installation on OS $NAME version $VERSION ...\n"
sleep 2

sudo apt-get update -y
if [ $? != 0 ]; 
then
echo "aptitude is in use by someone else (maybe the system itself) - please retry later - exiting.."
exit 1
fi
sudo apt-get install ca-certificates curl gnupg lsb-release -y
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update -y
sudo apt-get install docker-ce docker-ce-cli containerd.io -y
sudo apt-get install docker-compose -y
sudo apt-get install httpie jq -y
sudo service docker start
echo -e "\nOS installation part finished - switching over to Docker sub-process ...\n"
sleep 10
### /UBUNTU ###

elif [[ $NAME == *"CentOS Stream"* ]] && [[ $VERSION == *"8"* ]]; then
### CENTOS Streams ###

# Confirm installation on unsupported OS 
    while true; do

    echo -e "You are running this script on an unsupported machine: $NAME. It is recommended to use an Ubuntu Server LTS";
    read -p "Do you want to proceed with the installation on an unsupported Linux distribution? (y/n)" yn

    case $yn in 
        #If input is yes we leave the loop
        [yY] ) echo "Ok, we will continue with installation  ...";
            mkdir -p /etc/helmut4
            file_path="/etc/helmut4/unsupportedOS"
            current_date_time=$(date)
            echo "Installation on unsupported OS - $current_date_time" > "$file_path"
            break;;
        
        #No - abport binary installaton
        [nN] ) 
            echo -e "\nSkipping installation!";
            exit 1;;
        
        #If input is neither y nor n
        * ) echo "Invalid response for question";
        echo -e "\nManual abortion of installation!";
        exit 1;;
    esac
    done

echo -e "\nStarting the Helmut4-Media Downloader installation on OS $NAME version $VERSION ...\n"
sleep 2

sudo yum update -y
sudo yum install -y yum-utils device-mapper-persistent-data lvm2 nano
sudo yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm

sudo yum update -y

sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
sudo yum update -y --nobest --allowerasing
sudo yum install -y docker-ce docker-ce-cli containerd.io --nobest --allowerasing

sudo yum -y install httpie jq
sudo systemctl start docker
sudo systemctl enable /usr/lib/systemd/system/docker.service

echo -e "\nOS installation part finished - switching over to Docker sub-process ...\n"
sleep 10
### /CENTOS Streams###

elif [[ $NAME == *"CentOS"* ]] && [[ $NAME != *"CentOS Stream"* ]]; then
### CENTOS 7 ###

# Confirm installation on unsupported OS 
    while true; do

    echo -e "You are running this script on an unsupported machine: $NAME. It is recommended to use an Ubuntu Server LTS";
    read -p "Do you want to proceed with the installation on an unsupported Linux distribution? (y/n)" yn

    case $yn in 
        #If input is yes we leave the loop
        [yY] ) echo "Ok, we will continue with installation  ...";
            mkdir -p /etc/helmut4
            file_path="/etc/helmut4/unsupportedOS"
            current_date_time=$(date)
            echo "Installation on unsupported OS - $current_date_time" > "$file_path"
            break;;
        
        #No - abport binary installaton
        [nN] ) 
            echo -e "\nSkipping installation!";
            exit 1;;
        
        #If input is neither y nor n
        * ) echo "Invalid response for question";
        echo -e "\nManual abortion of installation!";
        exit 1;;
    esac
    done

echo -e "\nStarting the Helmut4-Media Downloader installation on OS $NAME version $VERSION ...\n"
sleep 2

sudo yum update -y
sudo yum --enablerepo=extras install epel-release -y
sudo yum update -y
sudo yum install -y yum-utils device-mapper-persistent-data lvm2 nano
sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo 
sudo yum update -y
if [[ $(rpm --eval '%{centos_ver}') == "8" ]]; then
sudo yum install -y docker-ce docker-ce-cli containerd.io --nobest
pip3 install httpie
pip3 install docker-compose
else
sudo yum install -y docker-ce docker-ce-cli containerd.io
sudo yum install -y httpie docker-compose
fi
sudo yum -y install jq
sudo systemctl start docker
sudo systemctl enable /usr/lib/systemd/system/docker.service

echo -e "\nOS installation part finished - switching over to Docker sub-process ...\n"
sleep 10
### /CENTOS ###

else
echo "Unknown or unsupported operating system - only Ubuntu, Debian and CentOS 7/8/Streams 8 is supported - exiting.."
exit 1
fi

echo -e "\nStarting configuring Helmut4 Media Downloader \n"
### GENERAL ###
touch /etc/localtime
touch /etc/timezone

# -> Portainer CE latest v2.x.x
docker run -it -d --restart=always -p 9000:9000 --name=portainer -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer-ce:lts --admin-password='$2y$05$WbcqfTqVa2T58lGrLO7Tp.30DMjKFo.6O4.XAmfBFg4a0jrVSbdW.' -H unix:///var/run/docker.sock
sleep 10
docker swarm init
docker swarm init --advertise-addr 127.0.0.1
docker swarm ca --cert-expiry 175200h --rotate

#Create folder for certificates
mkdir /root/certs


echo -e "\nDeploying Helmut4 Media Downloader stack file ...\n"

JWT=$(http --ignore-stdin POST :9000/api/auth Username="admin" Password="admin" | jq -r ".jwt")
SWARM_ID=$(http --ignore-stdin GET :9000/api/endpoints/1/docker/swarm "Authorization:Bearer ${JWT}" | jq -r ".ID")
http --ignore-stdin POST ":9000/api/registries" "Authorization:Bearer ${JWT}" Name="MoovIT GmbH" URL="repo.moovit24.de:443" Type:=3 Authentication:=true Username="moovit" Password="public"
echo -e "\nDeploying the Helmut4-Media Downloader Stack, this might take some time.. (Timeout is set to 10 minutes)\n"
STACK=$(curl -s https://repo.moovit24.de/install/config/custom-components-compose.yml)
http --ignore-stdin --timeout=1200 POST ":9000/api/stacks?method=string&type=1&endpointId=1" "Authorization:Bearer ${JWT}" Name="helmut4-mediadownloader" SwarmID="${SWARM_ID}" StackFileContent="${STACK}"


echo -e "Helmut4-Media Downloader setup done - you might want to change the portainer password from admin:admin to something more secure...\n\n\n"


echo -e "\n\n\nYour Helmut4-Media Downloader stack has been configured. Please go to Portainer and start to configure it towards your environment"
