#!/bin/sh

set -eu

# Error helper. See EXIT STATUS below.
die() {
    printf "fpkglist: %b\n" "$*" >&2
    exit 1
}

## NAME
##     fpkglist - list installed packages in a project directory
##
## SYNOPSIS
##     fpkglist TARGET
##

usage() {
    die "Usage: fpkglist TARGET"
}

## DESCRIPTION
##     fpkglist prints the names and versions of packages
##     installed in TARGET. It scans the fpkg/ metadata
##     directory created by fpkginstall.
##
## OPERANDS
##     fpkglist requires one operand.
##

if test $# -ne 1; then
    usage
fi

##     TARGET
##         Directory where the packages are installed.
##
##         Examples:
##             .
##             ~/sites/example.com
##             /opt/example.com
##

target=$1

if test ! -d "$target"; then
    die "target not a directory"
fi
if test ! -r "$target"; then
    die "target not readable"
fi

## EXIT STATUS
##     0   Success. The packages were listed.
##     1   Failure. Invalid arguments or error accessing TARGET.
##

metadir="$target/fpkg"

if test ! -e "$metadir"; then
    # No packages installed yet.
    exit 0
fi
if test ! -d "$metadir"; then
    die "meta directory not a directory: $metadir"
fi
if test ! -r "$metadir"; then
    die "meta directory not readable: $metadir"
fi

for pkg in "$metadir"/*; do
    if test -d "$pkg"; then
        if test ! -f "$pkg/VERSION"; then
            die "missing VERSION in $pkg"
        fi
        if test ! -r "$pkg/VERSION"; then
            die "unreadable VERSION in $pkg"
        fi
        name=$(basename "$pkg")
        version=$(cat "$pkg/VERSION")
        printf "%s-%s\n" "$name" "$version"
    fi
done

## EXAMPLES
##     List installed packages in ./myproject:
##
##         fpkglist myproject/
##
## SEE ALSO
##      fpkginstall, fpkgremove
