#!/usr/bin/bash
#
# SPDX-License-Identifier: GPL-3.0-or-later

LIBDIR=${LIBDIR:-'/usr/share/artools/lib'}

# shellcheck source=src/lib/base/message.sh
source "${LIBDIR}"/base/message.sh
# shellcheck source=src/lib/pkg/yaml.sh
source "${LIBDIR}"/pkg/yaml.sh

# shellcheck disable=1091
source "${MAKEPKG_LIBRARY}"/util/pkgbuild.sh
# shellcheck disable=1091
source "${MAKEPKG_LIBRARY}"/util/schema.sh

#{{{ functions

srcyaml_write_attr(){
    local ident1="$1" ident2="$2" ident3="$3"
    local attrname=$4 attrvalues=("${@:5}")

    # normalize whitespace, strip leading and trailing
    attrvalues=("${attrvalues[@]//+([[:space:]])/ }")
    attrvalues=("${attrvalues[@]#[[:space:]]}")
    attrvalues=("${attrvalues[@]%[[:space:]]}")

    case $attrname in
        pkgver|pkgrel|epoch|url|install|changelog)
            for v in "${attrvalues[@]}"; do
                Yaml+=$(write_yaml_map "$ident3" "$attrname" "$v")
            done
        ;;
        pkgdesc)
            Yaml+=$(write_yaml_map "$ident1" "$attrname" "${attrvalues[@]}")
        ;;
        *)
            Yaml+=$(write_yaml_map "$ident1" "$attrname")
            for v in "${attrvalues[@]}"; do
                Yaml+=$(write_yaml_seq "$ident2" "$v")
            done
        ;;
    esac
}

pkgbuild_extract_to_yaml() {
    local pkgname=$1 attrname=$2 isarray=$3 outvalue=

    if get_pkgbuild_attribute "$pkgname" "$attrname" "$isarray" 'outvalue'; then
        [[ -z $pkgname ]] && srcyaml_write_attr 2 4 2 "$attrname" "${outvalue[@]}"
        [[ -n $pkgname ]] && srcyaml_write_attr 4 6 2 "$attrname" "${outvalue[@]}"
    fi
}

srcyaml_write_section_details() {
    local attr package_arch a
    local multivalued_arch_attrs=(source provides conflicts depends replaces
                                  optdepends makedepends checkdepends
                                  "${known_hash_algos[@]/%/sums}")

    for attr in "${singlevalued[@]}"; do
        pkgbuild_extract_to_yaml "$1" "$attr" 0
    done

    for attr in "${multivalued[@]}"; do
        pkgbuild_extract_to_yaml "$1" "$attr" 1
    done

    get_pkgbuild_attribute "$1" 'arch' 1 'package_arch'
    for a in "${package_arch[@]}"; do
        # 'any' is special. there's no support for, e.g. depends_any.
        [[ $a = any ]] && continue

        for attr in "${multivalued_arch_attrs[@]}"; do
            pkgbuild_extract_to_yaml "$1" "${attr}_$a" 1
        done
    done
}

yaml_write_global() {
    local singlevalued=(pkgdesc pkgver pkgrel epoch url install changelog)
    local multivalued=(arch groups license checkdepends makedepends
                        depends optdepends provides conflicts replaces
                        noextract options backup
                        source validpgpkeys "${known_hash_algos[@]/%/sums}")

    Yaml+=$(write_yaml_map 0 "pkgbase")
    Yaml+=$(write_yaml_map 2 "name" "${pkgbase:-${pkgname}}")

    srcyaml_write_section_details ""
}

yaml_write_package() {
    local singlevalued=(pkgdesc url install changelog)
    local multivalued=(arch groups license checkdepends depends optdepends
                       provides conflicts replaces options backup)

    Yaml+=$(write_yaml_map 0 "pkgnames")
    for pkg in "${pkgname[@]}"; do
        Yaml+=$(write_yaml_seq_map 2 "pkgname" "$pkg")
        srcyaml_write_section_details "$pkg"
    done
}

write_srcyaml() {
    Yaml=$(write_yaml_header)
    yaml_write_global
    yaml_write_package

#     local version
#     version=$(get_full_version)
#     Yaml+=$(write_yaml_map 2 "version" "${version}")

    printf '%s\n' "${Yaml}"
}

#}}}

usage() {
    printf 'Usage: %s [options]\n' "${0##*/}"
    printf '    -h            This help\n'
    printf '\n'
    exit "$1"
}

# shellcheck source=config/makepkg/x86_64.conf
load_makepkg_config

opts='h'

while getopts "${opts}" arg; do
    case "${arg}" in
        h|?) usage 0 ;;
    esac
done

shift $(( OPTIND - 1 ))
srcpath=$(readlink -f "$1")

[[ -f "$srcpath"/PKGBUILD ]] || die "%s/PKGBUILD does not exist!" "$srcpath"

# shellcheck source=contrib/makepkg/PKGBUILD.proto
source "$srcpath"/PKGBUILD

write_srcyaml
