#!/bin/bash

function SCRIPT() {
    pkg_dir=$1

    if [ -z "$pkg_dir" ] || [ ! -d "$pkg_dir" ]; then
        echo "Usage: ipkg-make-index <package_directory>" >&2
        exit 1
    fi

    empty=1

    for pkg in $(find "$pkg_dir" -maxdepth 1 -name '*.ipk' | sort); do
        empty=
        name="${pkg##*/}"
        name="${name%%_*}"
        [[ "$name" = "kernel" ]] && continue
        [[ "$name" = "libc" ]] && continue

        echo "Generating index for package $pkg" >&2

        file_size=$(stat -L -c%s "$pkg")

        sha256sum=$(sha256sum "$pkg" | awk '{print $1}')

        # Make the package name sed-safe
        sed_safe_pkg=$(echo "$pkg" | sed -e 's/^\.\///g' -e 's/\\//\\\\\\//g')

        tar -xzOf "$pkg" ./control.tar.gz | tar xzOf - ./control | sed -e "s/^Description:/Filename: $sed_safe_pkg\\
Size: $file_size\\
SHA256sum: $sha256sum\\
Description:/"
        echo ""
    done
    [ -n "$empty" ] && echo
}

function pkg() {
    mkdir -p old

    for ipk in $(ls *.ipk); do
        if [ "$(echo "$ipk" | cut -d _ -f 1 | xargs -I{} find ./ -maxdepth 1 -type f -name {}_*)" ]; then
            echo "$ipk" | cut -d _ -f 1 | xargs -I{} find ./ -maxdepth 1 -type f -name {}_* | xargs ls -t | sed -n '2,$p' | xargs -I{} mv -f {} old/
        fi
    done
    SCRIPT . > Packages.manifest || true
    grep -vE '^(Maintainer|LicenseFiles|Source|Require)' Packages.manifest > Packages
    gzip -9nc Packages > Packages.gz

    # Add signature step
    gpg --detach-sign --armor -o Packages.sig Packages
    usign -S -m Packages -s /home/kenzo/key-build  # Ensure the path is correct, don't place the private key in a public directory
}

# Generates package manifest
if [[ $1 == "all" ]]; then
    for packages in $(ls -d /www/wwwroot/dllkids.xyz/packages/*/); do
        cd "$packages" || exit
        pkg
    done
elif [[ -z $1 ]]; then
    pkg
else
    cd "/www/wwwroot/dllkids.xyz/packages/$1/" || exit
    pkg
fi
