#!/bin/sh
set -e

[ -n "$DEBUG" ] && set -x

doas apk update

if [ "$1" = 'aarch64-toolchain' ]; then
  aarch64-toolchain.sh

else
  # Set ENV for cross compile for aarch64
  if [ "$2" = "cross-arm64" ]; then
    ALPINE="v3.16"
    TARGET_ARCH=aarch64
    SUDO_APK=abuild-apk
    APORTS=/home/alpine/aports
    CBUILDROOT=/home/alpine/sysroot-aarch64

    mkdir -p $CBUILDROOT/etc/apk/keys
    doas apk -X https://dl-cdn.alpinelinux.org/alpine/${ALPINE}/main --no-cache --no-scripts -p $CBUILDROOT --initdb --allow-untrusted --arch aarch64 add alpine-base
    doas apk -X https://dl-cdn.alpinelinux.org/alpine/${ALPINE}/main --no-cache --arch aarch64 -p $CBUILDROOT --allow-untrusted add alpine-keys
    doas cp /etc/apk/keys/stefan@zero-downtime.net-61bb6bfb.rsa.pub ${CBUILDROOT}/etc/apk/keys
    doas cp /etc/apk/repositories ${CBUILDROOT}/etc/apk

    EXTRADEPENDS_TARGET="libgcc libstdc++ musl-dev fortify-headers libc-dev busybox"

    . /usr/share/abuild/functions.sh
    export CBUILD

    export GOARCH=arm64
    export GOOS=linux

    doas apk update -p $CBUILDROOT
  fi

  for pkg in ~/$1; do
    # If checksum is OK, build package
    APKBUILD=$pkg abuild verify && rc=$? || rc=$?
    if [ $rc -eq 0 ]; then
      CHOST=$TARGET_ARCH APKBUILD=$pkg abuild -r

    else
      APKBUILD=$pkg abuild checksum
      echo "Please update your APKBUILD with the following checksums after verification:"
      . $pkg && echo $sha512sums
    fi
  done
fi