#!/bin/bash

# Strict mode
set -euo pipefail

DATABASE_FILE="trivy-database.tar.xz"
CHANGELOG_FILE="trivy-database.changes"
#TRIVY_IMAGE_REPOSITORIES="public.ecr.aws/aquasecurity/trivy:latest,aquasec/trivy:latest"
TRIVY_DATABASE_REPOSITORIES="public.ecr.aws/aquasecurity/trivy-db:2,aquasec/trivy-db:2,ghcr.io/aquasecurity/trivy-db:2"
TRIVY_JAVA_DATABASE_REPOSITORIES="public.ecr.aws/aquasecurity/trivy-java-db:1,aquasec/trivy-java-db:1,ghcr.io/aquasecurity/trivy-java-db:1"

# Helper functions
log() {
    echo >&2 "$@"
}
idempotent_tar() {
    tar "$@" --sort=name --owner=root:0 --group=root:0 --mtime="0" --format=gnu
}
dbversion() {
    jq -r .UpdatedAt "$@" | sed -E 's/[a-zA-Z.:-]//g' | cut -c 1-12
}

if ! which jq >/dev/null 2>&1; then
    log "Do not have jq on the system. Please install jq."
    exit 1
fi
if ! which trivy >/dev/null 2>&1; then
    log "Do not have trivy on the system. Please install recent trivy."
    exit 1
fi

log "Downloading / Refreshing database"

trivy image --download-db-only --db-repository "$TRIVY_DATABASE_REPOSITORIES"
trivy image --download-java-db-only --java-db-repository "$TRIVY_JAVA_DATABASE_REPOSITORIES"

# Get the current database version (the latest update datestring)
DB_VERSION="$(dbversion "$HOME/.cache/trivy/db/metadata.json")"
if [[ ! $DB_VERSION =~ ^[0-9]{12}$ ]]; then
    log "Invalid format for Trivy db version: $DB_VERSION"
    exit 1
fi
JAVA_DB_VERSION="$(dbversion "$HOME/.cache/trivy/java-db/metadata.json")"
if [[ ! $JAVA_DB_VERSION =~ ^[0-9]{12}$ ]]; then
    log "Invalid format for Trivy java-db version: $JAVA_DB_VERSION"
    exit 1
fi
if (( DB_VERSION > JAVA_DB_VERSION )); then
    TRIVY_DB_VERSION="$DB_VERSION"
else
    TRIVY_DB_VERSION="$JAVA_DB_VERSION"
fi

log "Found database version: $TRIVY_DB_VERSION"

SPEC_FILE=scanner-databases.spec

rm -f newspec
cat $SPEC_FILE | while read xline
do
	echo "$xline" >> newspec
	if echo $xline | grep -i ^Summary:.*trivy ; then
		log "in trivy section"
		read version

		if echo $version | grep -Eq "^Version:\s*$TRIVY_DB_VERSION$" ; then
		    log "The database is up-to-date"
		    rm newspec
		    exit
		fi
		echo "Version:	$TRIVY_DB_VERSION" >> newspec
	fi
done
diff -u $SPEC_FILE newspec || true
mv newspec $SPEC_FILE

# Compress trivy database in an idempotent .tar.xz archive
log "Compressing database"
idempotent_tar -Jcf "$DATABASE_FILE" -C "$HOME/.cache/trivy/" db java-db
