#!/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"
FilecoinStation_DOCKER_COMPOSE_FILE="/opt/filecoin_station_install/docker-compose.yml"
FilecoinStation_CN_DOCKER_COMPOSE_FILE="/opt/filecoin_station_install/docker-compose-cn.yml"
COMPOSE_DIR="/opt/facmgr/service"
VAULT_DOCKER_COMPOSE_FILE="$COMPOSE_DIR/docker-compose-vault.yml"
SVC_DOCKER_COMPOSE_FILE="$COMPOSE_DIR/docker-compose.yml"

images=("mc" "kubo" "prox_mpd" "pin_service" "vault" "kes" "minio" "minio-token" "ipfs" "prox_ai_lite" "filecoin_station")



if [ "$retain_data" = true ]; then
  directories=(ipfs kes mpd pin_service vault vfs)
else
  directories=(ipfs kes minio mpd pin_service vault vfs)
fi

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 
[ -f /etc/cron.d/check_filecoin_station.sh ] && rm /etc/cron.d/check_filecoin_station.sh 
[ -f /etc/cron.d/check_prox_ai_lite.sh ] && rm /etc/cron.d/check_prox_ai_lite.sh

cron_jobs=("check_docker.sh" "check_filecoin_station.sh" "check_prox_ai_lite.sh")

# Check if each cron job exists in crontab
for job in "${cron_jobs[@]}"; do
    if crontab -l | grep -q "$job"; then
        rm -f "/etc/cron.d/$job"
    fi
done

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

function main {

    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 "Docker Compose files not found at $VAULT_DOCKER_COMPOSE_FILE."
    fi

    if [ -f "$FilecoinStation_DOCKER_COMPOSE_FILE" ]; then
        docker-compose -f "$FilecoinStation_DOCKER_COMPOSE_FILE" down --remove-orphans
    elif [ -f "$FilecoinStation_CN_DOCKER_COMPOSE_FILE" ]; then
        docker-compose -f "$FilecoinStation_CN_DOCKER_COMPOSE_FILE" down --remove-orphans
    else
        log "Docker Compose files not found at $FilecoinStation_DOCKER_COMPOSE_FILE."
    fi

    if [ -f "$DOCKER_COMPOSE_FILE" ]; then
        docker-compose -f "$DOCKER_COMPOSE_FILE" down --remove-orphans
    else
        log "Docker Compose file not found at $DOCKER_COMPOSE_FILE"
    fi
    for image in "${images[@]}"; do
      log "Processing image: $image"
      docker stop $(docker ps -a --format '{{.ID}} {{.Image}}' | grep "$image" | awk '{print $1}') >/dev/null 2>&1
      docker rm $(docker ps -a --format '{{.ID}} {{.Image}}' | grep "$image" | awk '{print $1}') >/dev/null 2>&1
      # cancel delete images 5.16
      #tags=$(docker images --format "{{.Repository}}:{{.Tag}}" | grep "$image")

      #for tag in $tags; do
      #  docker rmi -f "$tag" >/dev/null 2>&1
      #done
      #log "Image $image processed"
    done


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

    # Unmount directory if necessary
    if [ -d "$VFS_DIR" ]; then
      if [ "$VFS_DIR" = "$MOUNT_POINT" ]; then
        log "Directory $VFS_DIR is a mount point. Unmounting..."
        umount -l "$VFS_DIR"
      fi
    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

    for dir in "${directories[@]}"; do
        dir_path="${DataDIR}/${dir}"
        if [ -d "$dir_path" ]; then
            rm -rf "$dir_path"
            log "Deleted directory: $dir_path"
        else
            log "Directory does not exist: $dir_path"
        fi
    done
    log "Deleted $DataDIR."

    log "Reset successful"
} 


main


