#!/usr/bin/env bash
#
# $Id: prtcreate,v 1.1.2 2024/04/15 02:23:32 jmq Exp $
# (c) 2003 by Martin Opel <martin@obbl-net.de>
# (c) 2017--2024 by The CRUX Project
#
# May be redistributed and modified under the terms of the GPL
# only usable with CRUX Linux, version 1.0 or higher.
#
# USE AT YOUR OWN RISK
#
# This script creates a Pkgfile in the current working directory with
# all necessary header information fields and an empty build() function.
# The port name is the name of the current working directory.

template_dir="/usr/share/prtcreate"
templates=()
force_write=0

usage() {
    echo "invalid template: $1.  Available build systems are:"
    for t in "$template_dir"/*; do echo "  ${t##*/}"; done
    exit 1
}

while [ -n "$1" ]; do
    case "$1" in
      -h|--help) echo "Usage (in a new port directory): $0 [template]"
                   echo "See $template_dir for the available templates."
                   exit 0 ;;
     -f|--force) force_write=1 ;;
              *) if [ -f "$template_dir/$1" ]; then templates+=("$1");
                 else usage "$1"; fi ;;
    esac
    shift
done

if [ -f Pkgfile ] && [ "$force_write" = 0 ]; then
    echo "Pkgfile exists! Use -f to overwrite."
    exit 1
fi

if [ -f /etc/prtcreate.conf ]; then
    . /etc/prtcreate.conf
fi

cat <<EOF > Pkgfile
# Description:
# URL:
# Maintainer: $maintainer_line
# Depends on:

name=$(basename "$PWD")
version=
release=1
source=()

build() {
EOF

if [ "${#templates[@]}" -lt 1 ]; then
    echo "  cd \$name-\$version" >> Pkgfile
else
    for t in "${templates[@]}"; do
        cat "$template_dir/$t" >> Pkgfile
    done
fi

echo "}" >> Pkgfile
