#!/bin/bash

cron_start_docker() {

    # Add the cron job
    (crontab -l 2>/dev/null | grep -v "/etc/cron.d/check_docker.sh" ; echo "* * * * * /etc/cron.d/check_docker.sh") | crontab -

    # Create the script file and write the content
    script_file="/etc/cron.d/check_docker.sh"
    cat << 'EOF' > "$script_file"
#!/bin/bash

log_file="/var/log/start_docker.log"
COMPOSE_DIR="/opt/facmgr/service"
COMPOSE_FILE="$COMPOSE_DIR/docker-compose-vault.yml"
declare -A SERVICE_PORTS=(["prox_mpd"]=6007 ["ipfs"]=4001 ["pin_service"]=9091 ["minio"]=9000 ["minio-token"]=9000 ["vault"]=8200 ["kes"]=7373)


function is_port_open {
    local port=$1
    netstat -anp | grep -w "LISTEN" | grep -w "$port"
}

function start_service {
    local SERVICE_NAME=$1
    local PORT=${SERVICE_PORTS[$SERVICE_NAME]}

    echo "Starting $SERVICE_NAME..." >> "$log_file"
    cd $COMPOSE_DIR
    docker-compose -f $COMPOSE_FILE up -d $SERVICE_NAME

    echo "Waiting for $SERVICE_NAME to start..." >> "$log_file"
    sleep 10

    local MAX_RETRIES=30
    local TRIES=0
    while [ $TRIES -lt $MAX_RETRIES ]; do
        if is_port_open $PORT; then
            echo "$SERVICE_NAME started and is healthy." >> "$log_file"
            break
        else
            echo "Port $PORT is not open. Retrying..." >> "$log_file"
            sleep 10
            ((TRIES++))
        fi
    done

    if [ $TRIES -eq $MAX_RETRIES ]; then
        echo "Port $PORT is still not open after $TRIES attempts. Check the log file for details." >> "$log_file"
        exit 1
    fi
}


function prepare_service {
    local SERVICE_NAME=$1

    if [ "$SERVICE_NAME" == "kes" ]; then
        echo "Preparing $SERVICE_NAME by cleaning certificates..." >> "$log_file"
        rm -rf /data/kes/certs/*
        rm -rf /data/minio/certs/*
    elif [ "$SERVICE_NAME" == "prox_mpd" ]; then
        echo "Preparing $SERVICE_NAME by unmounting /data/vfs..." >> "$log_file"
        umount /data/vfs -l
    fi
}

function check_and_start_container {
    local SERVICE_NAME=$1


    if [ "$SERVICE_NAME" == "ipfs" ]; then
      local expected_image=$(grep "image:" $COMPOSE_FILE | grep -E "ipfs|kubo" | awk '{print $2}')
    elif [ "$SERVICE_NAME" == "minio" ]; then
      local expected_image=$(grep "image:" $COMPOSE_FILE | grep "minio" | grep -v "mc" | awk '{print $2}')
    else
      local expected_image=$(grep "image:" $COMPOSE_FILE | grep "$SERVICE_NAME" | awk '{print $2}')
    fi


    local current_image=$(docker inspect -f '{{.Config.Image}}' $SERVICE_NAME 2>/dev/null)
    local container_status=$(docker inspect -f '{{.State.Status}}' $SERVICE_NAME 2>/dev/null)
    echo "expected_image is $expected_image,current_image is $current_image,container_status is $container_status" >> "$log_file"
    if [ "$container_status" != "running" ]; then
        echo "[$(date +"%Y-%m-%d %H:%M:%S")] $SERVICE_NAME container is not running, starting it..." >> "$log_file"
        prepare_service $SERVICE_NAME
        docker stop $SERVICE_NAME >> "$log_file" 2>&1
        docker rm $SERVICE_NAME >> "$log_file" 2>&1
        start_service $SERVICE_NAME
    elif [ "$current_image" != "$expected_image" ]; then
        echo "[$(date +"%Y-%m-%d %H:%M:%S")] $SERVICE_NAME container is running with an unexpected image ($current_image), restarting it with the expected image ($expected_image)..." >> "$log_file"
        prepare_service $SERVICE_NAME
        docker stop $SERVICE_NAME >> "$log_file" 2>&1
        docker rm $SERVICE_NAME >> "$log_file" 2>&1
        start_service $SERVICE_NAME
    else
        echo "[$(date +"%Y-%m-%d %H:%M:%S")] $SERVICE_NAME container is running with the expected image ($current_image)." >> "$log_file"
    fi
}

function check_and_start_containers {
    check_and_start_container vault
    check_and_start_container kes
    check_and_start_container minio
    check_and_start_container prox_mpd
    check_and_start_container ipfs
}

svc_state=$(sqlite3 /var/lib/facmgr/db/facmgr.db "select svc_state from service;")
echo "svc service state is $svc_state" >> "$log_file"

if [ "$svc_state" = "finish" ]; then
    check_and_start_containers
fi

echo "[$(date +"%Y-%m-%d %H:%M:%S")] Container check and start script executed" >> "$log_file"
EOF

    # Make the script executable
    chmod +x "$script_file"
    #systemctl restart cron.service
}

cron_start_docker

