#!/bin/bash

LOCK_FILE=~/.publish-cves-to-website-hash.lock
HASH_CACHE=~/.publish-cves-to-website-hash

cd "${0%/*}"
cd ..
pwd

REPO=$(basename $(git rev-parse --show-toplevel))
if [[ ! $REPO =~ ^ubuntu-cve-tracker$ ]] ; then
    echo "Top level repository '$REPO' is not 'ubuntu-cve-tracker', exiting" >&2
    exit 1
fi

BRANCH=$(git branch | awk '/*/ {print$2}')
if [[ ! $BRANCH =~ ^master$ ]] ; then
    echo "Branch '$BRANCH' is not 'master', exiting" >&2
    exit 1
fi

CURRENT_HASH=$(git rev-parse HEAD)

if [[ -f $HASH_CACHE ]] ; then 
    PREVIOUS_HASH=$(cat $HASH_CACHE)

    if [ $CURRENT_HASH == $PREVIOUS_HASH ] ; then
        echo "No changes were found."
        echo "Previous commit hash: ${PREVIOUS_HASH}"
        echo "Current commit hash: ${CURRENT_HASH}"
        exit
    fi

    CONTAINING_BRANCH=$(git branch --contains $PREVIOUS_HASH | awk '/*/ {print$2}')

    if [[ ! $CONTAINING_BRANCH =~ ^master$ ]] ; then
        echo "Master branch does not contain commit '$PREVIOUS_COMMIT', exiting" >&2
        exit 1
    fi

    CHANGES=$(git diff --name-status --diff-filter=ACDMR ${PREVIOUS_HASH}.. | awk '{print $NF}')
else
    echo "No previous commit hash found"
    while true; do
        read -p "Do you want to import all of UCT? (y/n)" yn
        case $yn in
            [Yy]* ) CHANGES="active retired ignored/not-for-us.txt" ; break ;;
            [Nn]* ) exit  ;;
            * ) echo "Please answer yes or no" ;;
        esac
    done
fi

cleanup() {
    # save $? so it's not clobbered by the call to rm
    rc="$?"

    rm -f "$LOCK_FILE"
    exit "$rc"
}

# This solution is inspired by
# https://stackoverflow.com/questions/325628/how-to-avoid-race-condition-when-using-a-lock-file-to-avoid-two-instances-of-a-s
if (set -o noclobber; echo "$$" > $LOCK_FILE) 2> /dev/null;
then
    # This will cause the lock-file to be deleted when this script exits.
    trap cleanup INT TERM EXIT

    if [[ ${#CHANGES} -gt 45 ]] ; then
        DISPLAY_CHANGES="${CHANGES:0:45}..."
    else
        DISPLAY_CHANGES="${CHANGES}"
    fi

    echo Running ./scripts/publish-cves-to-website-api.py ${DISPLAY_CHANGES}

    echo

    if ./scripts/publish-cves-to-website-api.py --stop $CHANGES ; then
        echo "Writing current hash '$CURRENT_HASH' to $HASH_CACHE"
        rm $HASH_CACHE
        echo $CURRENT_HASH > $HASH_CACHE
    else
        echo "Failed" >&2
        exit 1
    fi
else
    echo "Failed to acquire lock-file: $LOCK_FILE."
    echo "Lock file held by process $(cat $LOCK_FILE)."
    exit 1
fi
