#!/bin/bash

# Configuration variables
LIBDIR='/usr/share/manjaro-arm-tools/lib'
BUILDCLEAN='true'
INSTALL_NEW='false'

# Import the library
source "${LIBDIR}/functions.sh"

# Configuration variables
CHROOTDIR="${BUILDDIR}/${ARCH}"
PKG_CACHE="${CHROOTDIR}/var/cache/pacman/pkg"

# Check for root
check_root

# Check is the script already running
check_running

# Available options
opt=":p:a:i:r:nb:kh"

while getopts "${opt}" arg; do
  case $arg in
    p)
      PACKAGE="${OPTARG%/}"
      ;;
    a)
      ARCH="${OPTARG}"
      ;;
    k)
      BUILDCLEAN=false
      ;;
    b)
      BRANCH="${OPTARG}"
      ;;
    i)
      ADD_PACKAGES="${OPTARG}"
      check_local_pkgs
      ;;
    n)
      INSTALL_NEW=true
      ;;
    r)
      CUSTOM_REPO="${OPTARG}"
     ;;
    \?)
      echo "Invalid option: -${OPTARG}"
      exit 1
      ;;
    h|?)
      usage_build_pkg
      exit 1
      ;;
    :)
      echo "Option -${OPTARG} requires an argument, aborting"
      exit 1
      ;;
  esac
done

enable_colors

# Both package and architecture are needed
if [ "x" == "x$PACKAGE" ]; then
  echo "Option -p must be specified, aborting"
  exit
fi

# Build the 'any' packages on aarch64
if [ $ARCH == "any" ]; then
    ARCH="aarch64"
fi

# Make sure only a known branch is used
check_branch

# Start the timer
timer_start=$(get_timer)
   
if [[ "$BUILDCLEAN" = "false" && ! -d $CHROOTDIR ]]; then
    msg "Rootfs not found, aborting; omit the -k option to generate a rootfs"
    exit 1
elif [[ "$BUILDCLEAN" = "true" ]]; then
    # Create the rootfs to build within
    create_rootfs_pkg
fi

# Build the package
build_pkg

# Export the package and clean up
export_and_clean
prune_cache

# Show the timer
show_elapsed_time "${timer_start}"

# EOF
