#!/usr/bin/env bash

# makepkg utility

set -eoux pipefail

# directory where all build related files will end up
build_dir=build

# prepares the build environment for `makepkg`
setup() {
  if [[ ! -d "$build_dir" ]]; then
    mkdir "$build_dir"
  fi

  cp -u PKGBUILD "$build_dir/PKGBUILD"
  pushd "$build_dir"
  trap popd EXIT
}

# generates `.SRCINFO` for an already build package
# requires: setup build
srcinfo() {
  makepkg --printsrcinfo > .SRCINFO
}

# checks `PKGBUILD` and the package for improvements and errors
# requires: setup build
check() {
  namcap PKGBUILD
  namcap "$(find -name "*.zst")"
}

# print information related to the package
# requires: setup build
info() {
  pacman -Qlp "$(find -name "*.zst")"
  pacman -Qip "$(find -name "*.zst")"
}

# installs the package with `pacman`
# requires: setup build
pac_install() {
  sudo pacman -U "$(find -name "*.zst")"
}

# cleans the build directory
# requires: setup
clean() {
  # `|| true` is used to ignore the error if a directory/file is missing
  rm -r src pkg || true
  rm *.zst *.tar.gz || true
}

# build the package with `makepkg`
# requires: setup
build() {
  makepkg -f
}

main() {
  setup

  #clean
  build
  check
  srcinfo
}

main "$@"
