#! /bin/sh -
#
# Gets information from packages to create a checklist for
# the installer of Dragora (also know as "tagfiles")
#
# Copyright (c) 2019 Matias Fonzo, <selk@dragora.org>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# USAGE: makeTags [directory]
#   e.g: makeTags i586/tools

set -e

getSize()
{
    lzip_output="$(plzip -tvvv "$1" 2>&1)"

    # To obtain the uncompressed, compressed size
    echo $lzip_output | awk '{ print $8 $10 }' | \
     while IFS=, read -r decompressed compressed
    do
        echo "Decompressed size $(( $decompressed / 1024 ))K, Compressed size $(( ${compressed%.} / 1024 ))K"
    done

    unset lzip_output
}

searchpath="$1"
searchpath="${searchpath:-.}"

echo "Deleting any previous (.tmp) tagfile ..."
find $searchpath -type f -name 'tagfile*' -exec rm -f '{}' +

umask 022

# Search all .tlz packages
for meta in $(find $searchpath -type f -name '*.tlz')
do
    # Ignore some package names
    case $meta in
    *_pass?*)
        echo "    ${meta}: Ignored."
        continue;
        ;;
    esac
    if test ! -e "${meta}.txt"
    then
        echo "Error ${meta##*/} does not have a meta tag file." 1>&2
        exit 99;
    fi

    meta="${meta}.txt"
    directory=$(dirname -- "$meta")
    category="${directory##*/}"

    # Determine output level for those series with sub-directories
    case $directory in
    */modules/* | */xorg/*)
        output_level=../
        parent_level="$(dirname -- $directory)"
        parent_level="$(basename -- $parent_level)"
        parent_level=${parent_level}_
        ;;
    esac

    echo "Extracting information from $meta ..."
    . $meta
    (
        cd -- "$directory"
        echo "    Adding information to ${output_level}tagfile-${parent_level}${category}.tmp"
        echo "${pkgname}:${blurb}:ON:Version ${pkgversion} - $(getSize $(basename -- "${meta%.txt}"))" \
         >> "${output_level}tagfile-${parent_level}${category}.tmp"
    )
    unset output_level parent_level
done

echo "Removing temporal tagfile(s) and sorting the final ones ..."
for tagfile in ./*/*/tagfile*.tmp
do
    LC_COLLATE=C sort -- "$tagfile" > "${tagfile%.tmp}"
    rm -f -- "$tagfile";			# Delete temporary tagfile.
done

echo "All done."

