#!/bin/bash
# Exit immediately if a command exits with a non-zero status
set -e

handle_lock_error() {
    echo "Detected APT lock error. Cleaning up and retrying..."
    sudo rm -f /var/lib/dpkg/lock
    sudo rm -f /var/lib/dpkg/lock-frontend
    sudo rm -f /var/cache/apt/archives/lock
    sudo dpkg --configure -a
    sleep 2
}

safe_apt_update() {
    local retries=5
    for ((i=1; i<=retries; i++)); do
        if sudo apt-get update; then
            return 0
        else
            echo "APT update failed. Attempt $i/$retries"
            handle_lock_error
        fi
    done
    echo "Failed to update APT after multiple retries. Exiting."
    exit 1
}

safe_apt_install() {
    local package="$1"
    local retries=5
    for ((i=1; i<=retries; i++)); do
        if sudo apt-get install -y "$package"; then
            return 0
        else
            echo "Installation of $package failed. Attempt $i/$retries"
            handle_lock_error
        fi
    done
    echo "Failed to install $package after multiple retries. Exiting."
    exit 1
}

setup_conversion_0() {
    echo "########## Installing dos2unix ##########"
    safe_apt_update
    safe_apt_install dos2unix
    safe_apt_install curl

    echo "########## Converting scripts to Unix line endings ##########"
    dos2unix install.sh deploy.sh third_party_sw.sh disable_ubuntu_update_popups.sh screen_performance.sh auto_prowatchlylogin.sh
}

setup_client_user_1() {
    if id "client" &>/dev/null; then
        echo "********** Sub-user 'client' already exists, skipping user creation **********"
    else
        echo "########## Creating a new sub-user 'client' ##########"
        sudo adduser --disabled-password --gecos "" client
        echo "client:helloclient" | sudo chpasswd
        sudo usermod -aG netdev client
    fi

    echo "########## Restricting access to system files for 'client' ##########"
    sudo chmod 700 /home/prowatchlyadmin
    sudo chmod 700 /root
    sudo chmod 755 /var/www

    sudo usermod -aG netdev client
}

setup_screen_performance_2() {
    echo "########## SLEEPING FOR 5 SECONDS ##########"
    sleep 5

    echo "########## Disabling screen blanking ##########"
    chmod +x screen_performance.sh
    bash ./screen_performance.sh

    echo "########## DISABLE UBUNTU UPDATE POPUPS ##########"
    chmod +x disable_ubuntu_update_popups.sh
    sudo ./disable_ubuntu_update_popups.sh
}

setup_installing_docker_n_software_3_2() {
    safe_apt_install ffmpeg
    echo "########## Installing Docker ##########"
    safe_apt_install docker.io

    echo "########## Starting and enabling Docker service ##########"
    sudo systemctl daemon-reload
    sudo systemctl start docker
    sudo systemctl enable docker

    echo "########## Adding the current user to the Docker group ##########"
    sudo usermod -aG docker $USER
    echo "prowatchlyadmin ALL=(ALL) NOPASSWD: ALL" | sudo tee /etc/sudoers.d/prowatchlyadmin

    echo "########## Installing Docker Compose ##########"
    if ! safe_apt_install docker-compose; then
        echo "Failed to install Docker Compose after retrying. Exiting."
        exit 1
    fi

    echo "########## Verifying Docker Compose installation ##########"
    docker-compose --version
}

setup_docker_registry_4() {
    REGISTRY_URL="server.gemmiz.com:5000"
    DOCKER_CONFIG_FILE="/etc/docker/daemon.json"

    echo "########## Creating Docker daemon configuration file ##########"
    echo "{
    \"insecure-registries\": [\"$REGISTRY_URL\"]
}" | sudo tee "$DOCKER_CONFIG_FILE" >/dev/null

    echo "########## Restarting Docker service ##########"
    sudo systemctl restart docker
}

setup_nginx_and_video_play_service_5() {
    echo "########## Installing Nginx ##########"
    safe_apt_update
    safe_apt_install nginx

    echo "########## Creating website directory at /var/www ##########"
    sudo mkdir -p /var/www

    echo "########## Configuring Nginx ##########"
    sudo tee /etc/nginx/sites-available/default >/dev/null <<EOL
server {
    listen 15003;

    error_log /var/log/nginx/production_error.log;
    access_log /var/log/nginx/production_access.log;

    location /events {
        alias /var/www/;
        index index.html;
    }
}
EOL

    echo "########## Restarting Nginx ##########"
    sudo systemctl restart nginx
}

setup_run_scrips_6() {
    echo "########## THIRD PARTY SOFTWARE INSTALLATION ##########"
    chmod +x third_party_sw.sh
    sudo ./third_party_sw.sh

    # echo "########## AUTO LOGIN INSTALLATION ##########"
    # chmod +x auto_ubuntulogin.sh
    # bash ./auto_ubuntulogin.sh

    # chmod +x auto_prowatchlylogin.sh
    # bash ./auto_prowatchlylogin.sh
}

setup_run_scrips_app_7() {
    echo "########## Running deploy.sh ##########"
    chmod +x deploy.sh
    sudo ./deploy.sh
}

main() {
    setup_conversion_0
    setup_screen_performance_2
    setup_installing_docker_n_software_3_2
    setup_docker_registry_4
    setup_nginx_and_video_play_service_5
    setup_run_scrips_6
    setup_client_user_1
    setup_run_scrips_app_7
    echo "########## Everything successfully installed. RESTART IS REQUIRED NOW. ##########"
}

main
