#!/usr/bin/env bash
# Desc: Upgrades and verfies ots files.
# Usage: check_ots.sh [file]
# Example: ./check_ots.sh foo.txt.ots
# Note: Only outputs stderr or stdout on upgrade or verify failures.
# Version 0.0.2
# Depends: Bash 5.1.16, GNU Coreutils 8.32 (date), ots 0.7.0

# Plumbing
yell() { echo "$0: $*" >&2; } # print script path and all args to stderr
die() { yell "$*"; exit 111; } # same as yell() but non-zero exit status
must() { "$@" || die "cannot $*"; } # runs args as command, reports args if command fails
check_givens() {
    if [[ ! -f $1 ]]; then die "FATAL:Not a file:$1"; fi;
    re=".ots$|.OTS$";
    if [[ ! "$1" =~ $re ]]; then die "FATAL:Not an OTS file extension:$1"; fi;
    if [[ $# -ne 1 ]]; then die "FATAL:Incorrect argument count:$#"; fi;
    if ! command -v ots 1>/dev/random 2>&1; then die "FATAL:Not found:ots"; fi;
};  # Check given assumptions
upgrade_ots() {
    # Depends: GNU Coreutils 8.32 (date), ots 0.7.0
    
    file_in="$1";
    file_bak="$file_in".bak ;

    # # Upgrade ots
    if [[ ! -f "$file_bak" ]]; then
        "$(which ots)" u "$file_in" 1>/dev/null 2>&1;
    else
        yell "ERROR:Upgrade failed due to existing backup:$file_bak";
    fi;
}; # Upgrades ots file
verify_ots() {
    # Depends: ots 0.7.0
    
    if ! ( ots v "$1" 1>/dev/random 2>&1 ); then
        yell "ERROR:Verification failed:$1";
        ots v "$1"; # Show error
    fi;
}; # Verify ots file
main() {
    must check_givens "$1";
    must upgrade_ots "$1";
    must verify_ots "$1";
}; 

main "$@";

# Author: Steven Baltakatei Sandoval
# License: GPLv3+

# ots 0.7.0
#   See https://opentimestamps.org/
