#!/bin/bash
#
# $Id: prtcheck,v 1.1.1.1 2003/08/27 11:43:05 opel Exp $
# (c) 2003, Martin Opel <mo@obbl-net.de>
# revised 2022 by John McQuah <jmcquah@disroot.org> to address FS#1763
#
# Utility to check a port for existence of .signature, .footprint and
# the mandatory fields in Pkgfile. See "man 1 prtcheck" for details
#
# May be redistributed and modified under the terms of the GPL
# only usable with CRUX Linux, version 1.0 or higher
#
# USE AT YOUR OWN RISK
#


msg() {
	echo -n -e "====> $1"
}

warn() {
	msg "WARNING: $1\n"
	excode=$(( excode+1 ))
}

error() {
	msg "ERROR: $1\n"
	exit -1
}

ok() {
	msg "$(basename "$PWD") ok"
}

get_filename() {
        if [[ "$1" =~ ^(http|https|ftp|file)://.*/(.+) ]]; then
                echo "${BASH_REMATCH[2]}"
        else
                echo "$1"
        fi
}

#
# read options
#
while [ $# -gt 0 ]; do
	if [ "$1" = "--root" ]; then
		convertfootprint="true"
	else
		error "unsupported option \"$1\""
	fi
	shift
done

((excode=0))

#
# Checking footprint
#
if [ ! -s .footprint ]; then
	error "no footprint found or empty footprint!"
fi
if [ "$convertfootprint" = "true" ]; then
	uid="$(id -nu)"
	gid="$(id -ng)"
	file=".footprint"
	<$file sed -e "s,$uid/$gid,root/root," > $file.tmp
	mv $file.tmp $file
fi
if [ "$( <.footprint cut -f 2 | grep -c -v "root/root" )" -gt 0 ]; then
	warn "non-root users found!\nrun \"prtcheck --root\" to convert footprint"
fi

#
# Checking Pkgfile
#
if [ ! -s Pkgfile ]; then
	error "no Pkgfile found or Pkgfile empty!"
fi
depends="$(<Pkgfile awk '/^# Depends on:/ {print gensub(/# Depends on:[[:blank:]]*(.*)/,"\\1","g",$0)}')"
if [ "$depends" = "" ]; then
	warn "no dependencies, please check!"
fi

desc="$(<Pkgfile awk '/^# Description:/ {print gensub(/# Description:[[:blank:]]*(.*)/,"\\1","g",$0)}')"
url="$(<Pkgfile awk '/^# URL:/ {print gensub(/# URL:[[:blank:]]*(.*)/,"\\1","g",$0)}')"
maintainer="$(<Pkgfile awk '/^# Maintainer:/ {print gensub(/# Maintainer:[[:blank:]]*(.*)/,"\\1","g",$0)}')"

[ -n "$desc" ] || nullvars+=" Description"
[ -n "$url" ] || nullvars+=" URL"
[ -n "$maintainer" ] || nullvars+=" Maintainer"

[ -z "$nullvars" ] || error "Pkgfile is missing the field(s):$nullvars"

#
# Checking .signature
#
[ -s .signature ] || error "no signature file!"
. Pkgfile
(( unsigned=0 ))

for f in Pkgfile .footprint; do
	if ! grep -q "($f)" .signature; then
		warn "$f not signed"
		unsigned=$(( unsigned+1 ))
	fi
done

for (( p=0; p<${#source[@]}; p++ )); do
	if [ -z "${renames[$p]}" ] || [ "${renames[$p]}" = "SKIP" ]; then
		renames[$p]=$( get_filename "${source[$p]}" )
	fi
	if ! grep -q "(${renames[$p]})" .signature; then
		warn "${renames[$p]} not signed"
		unsigned=$(( unsigned+1 ))
	fi
done

[ "$unsigned" = 0 ] || error "incomplete signature file"
[ "$excode" = 0 ] && ok || exit $excode