#!/bin/bash
#
# --- T2-COPYRIGHT-NOTE-BEGIN ---
# This copyright note is auto-generated by scripts/Create-CopyPatch.
# 
# T2 SDE: scripts/Create-CkSumPatch
# Copyright (C) 2004 - 2020 The T2 SDE Project
# Copyright (C) 1998 - 2003 ROCK Linux Project
# 
# More information can be found in the files COPYING and README.
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License. A copy of the
# GNU General Public License can be found in the file COPYING.
# --- T2-COPYRIGHT-NOTE-END ---

. scripts/functions.in
override=0
files=''

usage()
{
	echo "Usage:"
	echo "scripts/Create-CkSumPatch [options] <package-name>"
	echo "scripts/Create-CkSumPatch [options] <target-name>"
	echo "scripts/Create-CkSumPatch [options] <file-path>"
	echo " "
	echo "Options:"
	echo "    -override        Create new cksum if old one should be valid."
	echo "    -help            This."
}

while [ "$1" ]; do
    case "$1" in
	-override)   override=1 ; shift ;;
	-repository) files="$files `echo package/$2/*/*.desc`" ; shift ; shift ;;
	-*|-help)    usage ; exit
	             ;;
	target/*)    files="$files $arg" ; shift ;;
	*.desc)      files="$files $arg" ; shift ;;
	*)           files="$files `echo package/*/$1/$1.desc`" ; shift ;;
    esac
done

# cksum_file path-to-desc-or-target-file
cksum_file() {
    case "$1" in
	target/*)
	    has_D='cat'
	    sedscript='s,^[^ ]*  *$file,$newcksum $file,'
	    ;;
	*.desc)
	    has_D='fgrep "[D]" | sed "s/[[]D[^ ]*//"'
	    sedscript='s,\[D\]  *[^ ]*  *$file,[D] $newcksum $file,'
	    ;;
	*)
	    echo "!!! File type not recognized" >&2
	    return -1
    esac

    if [ ! -f "$1" ]; then
	echo "!!! File not found: $1" >&2
	return -1
    fi

    cp $1 /tmp/$$
    eval "egrep -v '^#' $1 | $has_D" | while read cksum file url args; do
	[ "$cksum" = 'X' ] && continue
	[ "$cksum" != '0' -a "$override" = '0' ] && continue

	gzfile=`source_file cksum $file $url $flags`
	bzfile="`bz2filename "$gzfile"`"
	if [ ! -f "$bzfile" ]; then
	    echo "!!! File not present: $bzfile" >&2
	    continue
	fi

	local ck="sha224"
	if [[ "$bzfile" = *.zst ]] || [[ "$bzfile" = *.tzst ]] ; then
		echo -n "$bzfile (zstd): " >&2
		newcksum="`zstd -d < $bzfile | ${ck}sum | cut -f1 -d' '`"
	else
		echo -n "$gzfile (raw): " >&2
		newcksum="`${ck}sum $gzfile | cut -f1 -d' '`"
	fi
	newcksum="$newcksum" # also support explict {$ck}
	echo "$newcksum" >&2

	if [ "$cksum" != 0 -a "$cksum" != "$newcksum" ]; then
	    echo "!!! Checksum of $file changed (was $cksum)." >&2
	fi

	eval "sed \"$sedscript\" -i /tmp/$$"
    done

    diff -u ./$1 /tmp/$$
    rm -f /tmp/$$
}

echo "Creating cksum.patch ..." >&2

for f in $files; do
    cksum_file $f
done
