#!/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"

# 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"
}

{
    wget http://dl.fogworks.io/facmgr/docker-compose.yml -O /opt/docker-compose.yml

    docker-compose -f /opt/docker-compose.yml down --remove-orphans

    systemctl restart docker 
    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"

    rm -rf "$DataDIR"
    log "Reset successful"
} | tee -a "$LOG_FILE"

