#!/bin/bash

keep_content=$(echo "$1" | tr '[:upper:]' '[:lower:]')

### Init Logging ###

log_folder="/var/log/colibri/dp"
mkdir -p $log_folder
timestamp=$(date --iso-8601=ns | sed -E 's/(.*),([0-9]{7}).*(\+|-.*)/\1.\2\3/')
log_file="uninstall_${timestamp}.log"
log_file_path="$log_folder/$log_file"

function Write_Log {
	message=$1
	severity=$2

	if [ "$severity" == "" ]; then severity="INFO"; fi
	timestamp=$(date --iso-8601=ns | sed -E 's/(.*),([0-9]{7}).*(\+|-.*)/\1.\2\3/')
	log_line="[$timestamp][${severity^^}]: $message"
	if [ "${severity^^}" == "ERROR" ] || [ "${severity^^}" == "WARNING" ]; then
		>&2 echo "$log_line" | tee -a "$log_file_path"
	else
		echo "$log_line" | tee -a "$log_file_path"
	fi
}

function Disable_Service {
    service=$1

    if systemctl is-active "$service" -q; then
        systemctl stop "$service" > /dev/null 2>&1
        systemctl disable "$service" > /dev/null 2>&1
    fi
}

function Remove_Apt_Package_If_Installed {
    pkg=$1
    query=$(dpkg-query -W --showformat='${Status}\n' $pkg 2>/dev/null | grep "install ok installed")
	if [ -n "$query" ]
	then
		apt purge $pkg -y
	fi
}

### End Init Logging ###

### Init variables ###

colibri_user="colibri_service_user"
local_colibri_root="/opt/colibri"
local_dp_folder="$local_colibri_root/dp"
local_ssh_folder="$local_colibri_root/ssh"
local_openssl_folder="$local_colibri_root/openssl"
local_nginx_folder="$local_colibri_root/nginx"
local_dp_db_folder="/var/lib/colibri_dp"
local_docker_folder="${local_dp_folder}/docker"
local_automount_folder="$local_colibri_root/automount"
local_repo_folder="$local_colibri_root/repositories"
local_cron_folder="/etc/cron.d"
local_automount_cron_task="$local_cron_folder/colibri_osimage_mount"

if [ -z "$keep_content" ] || [ "$keep_content" != "true" ]
then
	Write_Log "Distribution point files will be completely removed with content" "WARNING"
    keep_content="false"
fi

### End Init variables

if [ "$keep_content" == "false" ]; then
    Write_Log "Stop install script if started"
    # shellcheck disable=SC2046
    # shellcheck disable=SC2009
    kill -9 $(ps aux | grep "$local_dp_folder/docker/install.sh" | awk '{print $2}') > /dev/null 2>&1
fi

Write_Log "Stop host services nginx and samba"
Disable_Service nginx
Disable_Service smbd

Write_Log "Remove local repo tools if installed"
Remove_Apt_Package_If_Installed "aptly"
Remove_Apt_Package_If_Installed "createrepo"
Remove_Apt_Package_If_Installed "createrepo_c"
Remove_Apt_Package_If_Installed "genbasedir"

Write_Log "Remove DP services"
if [ -f "$local_docker_folder/docker-compose.yml" ]; then
    Write_Log "- Remove containers"
    docker compose -f "$local_docker_folder/docker-compose.yml" down --user "$colibri_user" > /dev/null 2>&1

    Write_Log "- Remove Images"
    # shellcheck disable=SC2046
    docker image rm -f $(docker images -aq colibri/*) --user "$colibri_user" > /dev/null 2>&1
else
    Write_Log "Compose file is not detected. Skipping containers removal" "WARNING"
fi

Write_Log "Remove Automount scripts. Keep content flag set to [$keep_content]"
if [ -d "$local_automount_folder" ] && [ "$keep_content" == "false" ]; then
    Write_Log "- Automount folder detected [$local_automount_folder]. Remove it recursively"
    rm -rf "$local_automount_folder"
fi

Write_Log "Remove SSH keys folder"
if [ -d "$local_ssh_folder" ]; then
    Write_Log "- SSH folder detected [$local_ssh_folder]. Remove it recursively"
    rm -rf "$local_ssh_folder"
fi

if [ -f "$local_automount_cron_task" ]; then
    Write_Log "- Automount cron task detected [$local_automount_cron_task]. Remove it forcefully"
    rm -f "$local_automount_cron_task"
fi

Write_Log "Umount images folders. Keep content flag set to [$keep_content]"
if [ -d "$local_repo_folder/osimages/" ]  && [ "$keep_content" == "false" ]; then
    umount "$local_repo_folder/osimages/"* >/dev/null 2>&1
fi

Write_Log "Cleanup repository content. Keep content flag set to [$keep_content]"
if [ -d "$local_repo_folder" ] && [ "$keep_content" == "false" ]; then
    Write_Log "- Repository root folder detected [$local_repo_folder]. Remove it recursively"
    rm -rf "$local_repo_folder"
fi

Write_Log "Remove docker folder"
if [ -d "$local_docker_folder" ]; then
    Write_Log "- docker folder detected [$local_docker_folder]. Remove it recursively"
    rm -rf "$local_docker_folder"
fi

Write_Log "Remove DP folder. Keep content flag set to [$keep_content]"
if [ -d "$local_dp_folder" ] && [ "$keep_content" == "false" ]; then
    Write_Log "- DP folder detected [$local_dp_folder]. Remove it recursively"
    rm -rf "$local_dp_folder"
fi

Write_Log "Remove DP database folder"
if [ -d "$local_dp_db_folder" ]; then
    Write_Log "- DP database folder detected [$local_dp_db_folder]. Remove it recursively"
    rm -rf "$local_dp_db_folder"
fi

Write_Log "Remove Nginx folder"
if [ -d "$local_nginx_folder" ]; then
    Write_Log "- Remove Nginx folder [$local_nginx_folder]. Remove it recursively"
    rm -rf "$local_nginx_folder"
fi

Write_Log "Remove OpenSSL folder"
if [ -d "$local_openssl_folder" ]; then
    Write_Log "- OpenSSL folder detected [$local_openssl_folder]. Remove it recursively"
    rm -rf "$local_openssl_folder"
fi

Write_Log "Remove Colibri service user"
if grep -qi "^$colibri_user:" /etc/passwd; then
    Write_Log "User detected"
    killall -u "$colibri_user" > /dev/null 2>&1
    userdel -rf "$colibri_user" > /dev/null 2>&1
fi