#!/bin/bash

# Set parameters

DataDIR="/data"
VFS_DIR="$DataDIR/vfs"
LOG_DIR="/var/log/facmgr"
LOG_FILE="$LOG_DIR/reset.log"
MOUNT_POINT=$(df -P "$VFS_DIR" | awk 'END{print $NF}')
SERVICE_FILE_PATH="/etc/systemd/system/facmgr_docker.service"
DOCKER_COMPOSE_FILE="/opt/prox_ai_install/docker-compose.yml"
VAULT_DOCKER_COMPOSE_FILE="/opt/facmgr_install/docker-compose-vault.yml"
SVC_DOCKER_COMPOSE_FILE="/opt/facmgr_install/docker-compose.yml"

retain_data=false

if [[ $# -eq 1 && $1 == "-r" ]]; then
    retain_data=true
fi

[ -f /etc/cron.d/check_docker.sh ] && rm /etc/cron.d/check_docker.sh  && systemctl restart cron

# Check if script is run as root
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" | tee -a "$LOG_FILE"
   exit 1
fi


if [ ! -d "$LOG_DIR" ]; then
  echo "Directory $DIR does not exist. Creating..." | tee -a "$LOG_FILE"
  mkdir -p "$LOG_DIR"
fi

function log {
    echo "$(date +"%Y-%m-%d %H:%M:%S") - $1" | tee -a "$LOG_FILE"
}

{
    systemctl restart docker 
    if [ -f "$VAULT_DOCKER_COMPOSE_FILE" ]; then
        docker-compose -f "$VAULT_DOCKER_COMPOSE_FILE" down --remove-orphans
    elif [ -f "$SVC_DOCKER_COMPOSE_FILE" ]; then
        docker-compose -f "$SVC_DOCKER_COMPOSE_FILE" down --remove-orphans
    else
        log "Error: Docker Compose files not found."
    fi


    if [ -f "$DOCKER_COMPOSE_FILE" ]; then
        docker-compose -f "$DOCKER_COMPOSE_FILE" down --remove-orphans
    else
        log "Error: Docker Compose file not found at $DOCKER_COMPOSE_FILE"
    fi

    docker stop $(docker ps -aq)
    docker rm $(docker ps -aq)
    docker image prune -a --force

    # Unmount directory if necessary
    if [ "$VFS_DIR" = "$MOUNT_POINT" ]; then
      log "Directory $VFS_DIR is a mount point. Unmounting..."
      umount -l "$VFS_DIR"
    fi

    rm -rf "$SERVICE_FILE_PATH"

    if [ "$retain_data" = true ]; then
        log "Deleting directories within $DataDIR except for 'minio'."
        find "$DataDIR" -mindepth 1 -maxdepth 1 -type d ! -name "minio" -exec rm -r {} \;
    else
        log "Not deleting $DataDIR. Only removing directories within $DataDIR except for 'minio'."
    fi

    if [ "$retain_data" = false ]; then
        rm -rf "$DataDIR"
        log "Deleted $DataDIR."
    fi

    log "Reset successful"
} | tee -a "$LOG_FILE"


