#!/bin/bash

# Color Definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m'

SCRIPT_NAME='startup.sh'
FPMA_SCRIPT="./$SCRIPT_NAME"
CLOUD_BUCKET_PATH='gs://fao-fpma-docker-scripts'

# Check gsutil Installation
check_gsutil() {
    if [[ $(which gsutil) && $(gsutil --version) ]]; then
        printf "${GREEN}gsutil installation verified${YELLOW}\n"
        which gsutil
        gsutil --version
        printf "${NC}"
    else
        printf "${RED}Error. Please make sure that gsutil is properly installed.\n${NC}"
        exit
    fi
}

# Function to self-update the script
self_update() {
    if test -f "$FPMA_SCRIPT"; then
        printf '\nBacking up old script...\n'
        mv "$FPMA_SCRIPT" "$FPMA_SCRIPT.$(date +'%Y%m%d%H%M')"
    fi

    printf '\nPulling latest script...\n'
    gsutil cp $CLOUD_BUCKET_PATH/"$SCRIPT_NAME" "$FPMA_SCRIPT.temp"

    if ! test -f "$FPMA_SCRIPT.temp"; then
        printf "${RED}Error downloading the script.\n${NC}"
        if test -f "$FPMA_SCRIPT.$(date +'%Y%m%d%H%M')"; then
            printf "Restoring backup...\n"
            mv "$FPMA_SCRIPT.$(date +'%Y%m%d%H%M')" "$FPMA_SCRIPT"
        fi
        exit 1 # Exit with an error code to indicate failure
    fi

    # At this point, the download was successful
    printf '\nGranting permissions...\n'
    chmod +x "$FPMA_SCRIPT.temp"

    printf '\nReplacing the script with the updated version...\n'
    mv "$FPMA_SCRIPT.temp" "$FPMA_SCRIPT"

    # Cleanup: Delete all backups
    printf '\nCleaning up backups...\n'
    rm -f "$FPMA_SCRIPT".*

    printf '\nUpdate completed.\n'
    source "$FPMA_SCRIPT" noupdate
}

# Check Docker Installation
check_docker() {
    if [[ $(which docker) && $(docker --version) && $(which docker-compose) && $(docker-compose --version) ]]; then
        printf "${GREEN}Docker installation verified${YELLOW}\n"
        which docker
        docker --version
        which docker-compose
        docker-compose --version
        printf "${NC}"
    else
        printf "${RED}Docker is not properly installed. Please visit <https://docs.docker.com/engine/install/${NC}\n>"
        exit
    fi
}

if [[ $1 != "noupdate" ]]; then
    check_gsutil
    self_update
    exit
fi
check_docker