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

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


function is_port_open {
    local port=$1
    if [[ $port -gt 0 ]]; then
            netstat -anp | grep ":$port\s" | grep "LISTEN"
    fi
}


start_service() {
    SERVICE_NAME=$1
    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

    # Check port status with retries
    MAX_RETRIES=30
    TRIES=0
    RETRY_FAILED_COUNT=0
    RETRY_INTERVAL=10
    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 $RETRY_INTERVAL
            TRIES=`expr $TRIES + 1`;
            RETRY_FAILED_COUNT=`expr $RETRY_FAILED_COUNT + 1`;
        fi
    done

    if [ $RETRY_FAILED_COUNT -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
}



# Check container status and start them
check_and_start_containers() {
    # Check minio container status

    expected_image=$(grep 'image:' /opt/facmgr/service/docker-compose-vault.yml | grep 'vault' | awk '{print $2}')

    vault_current_image=$(docker inspect -f '{{.Config.Image}}' vault 2>/dev/null)

    vault_status=$(docker inspect -f '{{.State.Status}}' vault 2>/dev/null)
    if [ "$vault_status" != "running" ]; then
        echo "[$(date +"%Y-%m-%d %H:%M:%S")] vault container is not running, starting it..." >> "$log_file"
        docker rm vault >> "$log_file" 2>&1
	docker stop vault >> "$log_file" 2>&1
        start_service vault >> "$log_file" 2>&1
    fi


    if [ "$vault_status" != "running" ]; then
      echo "[$(date +"%Y-%m-%d %H:%M:%S")] vault container is not running, starting it..." >> "$log_file"
      docker rm vault >> "$log_file" 2>&1
      start_service vault >> "$log_file" 2>&1
    elif [ "$current_image" != "$expected_image" ]; then
      echo "[$(date +"%Y-%m-%d %H:%M:%S")] vault container is running with an unexpected image ($current_image), restarting it with the expected image ($expected_image)..." >> "$log_file"
      docker stop vault >> "$log_file" 2>&1
      docker rm vault >> "$log_file" 2>&1
      start_service vault >> "$log_file" 2>&1
    else
      echo "[$(date +"%Y-%m-%d %H:%M:%S")] vault container is running with the expected image ($current_image)." >> "$log_file"
    fi


    kes_status=$(docker inspect -f '{{.State.Status}}' kes 2>/dev/null)
    if [ "$kes_status" != "running" ]; then
        echo "[$(date +"%Y-%m-%d %H:%M:%S")] kes container is not running, starting it..." >> "$log_file"
        rm -rf /data/kes/certs/*
        rm -rf /data/minio/certs/* 
	docker rm kes >> "$log_file" 2>&1
        docker stop kes >> "$log_file" 2>&1
        start_service kes >> "$log_file" 2>&1
    fi

    minio_status=$(docker inspect -f '{{.State.Status}}' minio 2>/dev/null)
    if [ "$minio_status" != "running" ]; then
        echo "[$(date +"%Y-%m-%d %H:%M:%S")] minio container is not running, starting it..." >> "$log_file"
        docker rm minio >> "$log_file" 2>&1
        docker stop minio >> "$log_file" 2>&1
        start_service minio >> "$log_file" 2>&1
    fi


    # Check prox_mpd container status
    prox_mpd_status=$(docker inspect -f '{{.State.Status}}' prox_mpd 2>/dev/null)
    if [ "$prox_mpd_status" != "running" ]; then
        echo "[$(date +"%Y-%m-%d %H:%M:%S")] prox_mpd container is not running, starting it..." >> "$log_file"
        umount /data/vfs -l
	docker rm prox_mpd >> "$log_file" 2>&1
        docker stop prox_mpd >> "$log_file" 2>&1
        start_service prox_mpd >> "$log_file" 2>&1
    fi


    ipfs_status=$(docker inspect -f '{{.State.Status}}' ipfs 2>/dev/null)
    if [ "$ipfs_status" != "running" ]; then
        echo "[$(date +"%Y-%m-%d %H:%M:%S")] ipfs container is not running, starting it..." >> "$log_file"
        docker rm ipfs >> "$log_file" 2>&1
        docker stop ipfs >> "$log_file" 2>&1
        start_service ipfs >> "$log_file" 2>&1
    fi
}



result=$(sqlite3 /var/lib/facmgr/db/facmgr.db "select svc_state from service;")

echo "svc service state is $result" >> "$log_file"
if [ "$result" = "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



