#!/bin/sh
set -eu

# A hacky script to generate .pkg.tar.?z files using satellites.
# It's a fairly simple wrapper to astronaut, that generates pacman packages.

# This may also serve as an example on how you can wrap astronaut to package in any format.
# Sure, no dependency resolution, and the packages won't make it in any official repositories,
#   but it isn't meant for that anyway.

# Find astronaut
_astronaut="$(dirname "$0")/astronaut"
[ ! -f "$_astronaut" ] && _astronaut="astronaut"

# Configuration
wrapper_pacman_dir="$PWD"  # Where the packages should be stored

# Wrapper functions
_astronaut_wrapper_pre() {
    # Make sure to remove the contents of the install directory before building
    _astronaut_nuke_install=true
}

_astronaut_wrapper_post() {
    # Create the package info file
    cat > "$dir_install/.PKGINFO" << EOF
pkgname = $name_sat
pkgver = $version-astro
pkgdesc = Generated with pacman-astronaut
url = $update_url
builddate = $(date -u '+%s')
size = $(du -sb --apparent-size "$dir_install" | awk '{print $1}')
arch = $(uname -m)
EOF

    mkdir -p "$wrapper_pacman_dir"
    cd "$wrapper_pacman_dir"

    # Create the package
    bsdtar --strip-components 1 -C "$dir_install" -czf .MTREE --format=mtree --options='!all,use-set,type,uid,gid,mode,time,size,md5,sha256,link' .
    mv .MTREE "$dir_install/.MTREE"  # bsdtar doesn't like the file being in the same directory.
    fakeroot -- bsdtar --strip-components 1 -C "$dir_install" -cf - . > "$name_sat-$version-astro-$(uname -m).pkg.tar"
    repo-add astronaut.db.tar.gz "$name_sat-$version-astro-$(uname -m).pkg.tar"
}

. "$_astronaut"