#!/bin/bash

CONTAINER_NAME=llink
CURRENT_VERSION=$(sudo docker image ls --filter "reference=${CONTAINER_NAME}" --format "{{.Tag}} {{.CreatedAt}}" | grep -v "^latest" | sort -r -k2 | head -n 1 | awk '{print $1}'
)

increment_container_version() {
        if [[ $CURRENT_VERSION =~ ^v([0-9]+)\.([0-9]+)$ ]]; then
        MAJOR=${BASH_REMATCH[1]}
        MINOR=${BASH_REMATCH[2]}
        NEXT_VERSION="v${MAJOR}.$((MINOR + 1))"
    else
        NEXT_VERSION="Invalid format"
    fi

    echo "Current version: $CURRENT_VERSION"
    echo "Next version (if Enter is pressed): $NEXT_VERSION"
    echo -n "Press Enter to increment, or type a new version to overwrite: "
    read INPUT

    if [[ -z "$INPUT" ]]; then
        # Increment the version
        if [[ $CURRENT_VERSION =~ ^v([0-9]+)\.([0-9]+)$ ]]; then
            MAJOR=${BASH_REMATCH[1]}
            MINOR=${BASH_REMATCH[2]}
            MINOR=$((MINOR + 1))
            CURRENT_VERSION="v${MAJOR}.${MINOR}"
        else
            echo "Error: Invalid version format. Resetting to v1.0."
            CURRENT_VERSION="v1.0"
        fi
    else
        # Overwrite the version
        CURRENT_VERSION="$INPUT"
    fi

    echo "Updated version: $CURRENT_VERSION"
}

stop_container() {
    if sudo docker ps --filter "name=$CONTAINER_NAME" --filter "status=running" | grep -q "$CONTAINER_NAME"; then
            echo "Stopping running container: $CONTAINER_NAME"
            sudo docker stop "$CONTAINER_NAME"
    fi
}

build_new_container_image() {
    cd /home/silklaasboer/config/llink
    echo "Rebuilding container with updated image"
    sudo docker build -t ${CONTAINER_NAME}:${CURRENT_VERSION} .
}

create_new_container_tag() {
    echo "Updating container tag with updated image"
    sudo docker rmi -f ${CONTAINER_NAME}:latest
    sudo docker tag ${CONTAINER_NAME}:${CURRENT_VERSION} ${CONTAINER_NAME}:latest
}

start_container() {
    #mandatory for now bc dockercompose is in another dir
    cd /home/silklaasboer/docker
    echo "Starting container with updated image"
    sudo docker compose up -d llink
}

image_cleanup() {
    local image_count=$(docker images --format "{{.Repository}}:{{.Tag}}" | grep "${CONTAINER_NAME}" | wc -l)

    if (( image_count > 5 )); then
        echo "More than 5 images found for ${CONTAINER_NAME}. Cleaning up..."
        docker images --format "{{.Repository}}:{{.Tag}} {{.CreatedAt}}" \
            | grep "${CONTAINER_NAME}" \
            | sort -k2 \
            | head -n $((image_count - 5)) \
            | awk '{print $1}' \
            | xargs -r docker rmi -f
        echo "Old images removed."
    fi
}

increment_container_version
stop_container
build_new_container_image
create_new_container_tag
start_container
image_cleanup






