#!/bin/busybox ash
# shellcheck shell=ash
#
# Required packages (names are Alpine Linux pkgs):
# busybox - for grep, sed, tr, and other simple utiltiies
# curl - for fetching the patch

print() {
    printf -- "\033[0m\033[32m>>>\033[0m %s\n" "$*"
}

APKBUILD_LINT=apkbuild-lint

help() {
	cat <<__EOF__
usage: ${0##*/} [-h] [-p path] <APKBUILD...>

keys:
  -h			
    print this message
  -p path	
    path to apkbuild-lint binary used to find violations
__EOF__
}

for arg; do
	case "$arg" in
		-h) # Print help message and exit
			help
			exit 0
			;;
		-p) # Set the binary location to a value given to us by the user
			APKBUILD_LINT="$2"
			shift
			shift
			;;
		--) # End of options
			shift
			break
			;;
		*) # No more options after the file file is given
			shift
			set -- "$@" "$arg"
			;;
	esac
done

ret=0
for apkbuild; do

    # Deal with relative and absolute paths
    case "$apkbuild" in
        /*|./*);;
        *) apkbuild=./"$apkbuild"
    esac

	# Source the apkbuild, required to get pkgname
	srcdir="" . "$apkbuild" || {
		echo "Failed to source APKBUILD in '$apkbuild'" ;
		exit 1;
	}

    # Store all volatile sources we have
	violations="$("$APKBUILD_LINT" "$apkbuild" | grep -F 'SC:[AL62]')"
	[ -z "$violations" ] && exit 0

    # Loop over every violation
    printf -- "%s\\n" "$violations" | while IFS=: read -r _ _ _ l v; do
        # Get the URL
        v="$(printf -- "%s\\n" "$v" | sed 's|volatile source ||g' | tr -d "'")"

        # Store the URL separately
        url="$v"

        filename=""
        # Check if we are given a filename
        if printf -- "%s\\n" "$v" | grep -q '::'; then
            filename="$(printf -- "%s\\n" "$v" | cut -d : -f1)".patch
            url="$(printf -- "%s\\n"" $v" | cut -d : -f3)" # 3rd field is after the '::'
        else
            filename="${v##*/}" # Basename of the URL
        fi

        print "fetching '$url'"

        # Download the patch with curl
        path="${apkbuild%/*}"/"$filename"
        curl --silent --location "$url" --output "$path" || {
            echo "Failed to download patch from '$url'" >&2;
            # TODO: add 1 to ret if it fails here and continue to next iteration
            # of the loop, this allows us to process all URLs instead of failing
            # at the first one
            exit 1;
        }

        # Replace the URL in source=, this is not perfect but good enough
        sed -i "{$l s|$v|$filename| }" "$apkbuild"

        print "replaced with '$filename'"
    done

done
exit $ret
