#!/bin/bash


readonly KERNEL_VER=6.5.8
readonly KERNEL_LTS_VER=5.15.88
readonly CHROOT_NAMES=( armv7h i686 x86_64 )
readonly ABS_ROOT=/var/lib/archbuild/abslibre # no spaces
readonly ABS_UPSTREAM=parabola
readonly PKG_DIRS=( ${ABS_ROOT}/libre/acpi_call{-dkms,,-lts}   # -dkms first
                    ${ABS_ROOT}/libre/tp_smapi{,-lts}        ) # no trailing slashes
readonly PKGBUILDS=( ${PKG_DIRS[*]/%/\/PKGBUILD} )


Main()
{
  local chroot pkg_dir kver pkgname pkgver pkgrel arches chroot_dir arch
  local pkgs=()
  local all_pkgs=()
  local commit_msg=''

  echo -e "\nupgrading chroots\n"
  for chroot in ${CHROOT_NAMES[*]}
  do  sudo librechroot -n ${chroot} update || exit 1
  done

  echo -e "\nbuilding packages\n"
  for pkg_dir in ${PKG_DIRS[*]}
  do  kver=$( [[ "${pkg_dir}" =~ -lts$ ]] && echo ${KERNEL_LTS_VER} || echo ${KERNEL_VER} )
      pkgs=()

      [[ -d "${pkg_dir}" && -f "${pkg_dir}"/PKGBUILD ]] ||
      ! echo "${pkg_dir} - no such PKGBUILD"            || continue

      cd ${pkg_dir}/ ; git checkout HEAD PKGBUILD &> /dev/null ;

      pkgname=$(source PKGBUILD ; echo ${pkgname} ;)
      pkgver=$( source PKGBUILD ; echo ${pkgver}  ;)
      pkgrel=$( source PKGBUILD ; echo ${pkgrel}  ;)
      arches="$(source PKGBUILD ; echo ${arch[*]} ;)"
      ! [[ "${pkgrel}" =~ \.basekernel${kver}$ ]] ||
      ! echo "${pkg_dir} - skipping PKGBUILD"     || continue

      sed -i "s|^_basekernel=.*|_basekernel=${kver}|" PKGBUILD
      pkgrel=$( source PKGBUILD ; echo ${pkgrel}  ;)
      [[ "${pkgrel}" =~ \.basekernel${kver}$ ]]          ||
      ! echo "ERROR: ${pkg_dir} - PKGBUILD not modified" || continue

      for chroot in ${CHROOT_NAMES[*]}
      do  chroot_dir=$(librechroot -n ${chroot} |& grep -E 'copydir +: ' | cut -d: -f2)
          arch=$(source ${chroot_dir}/etc/os-release ; sed 's|-.*||' <<<${VARIANT_ID})
          [[ -n "${arch}" && " ${arches} " =~ " ${arch} " ]] || continue

          echo "building pkgname: ${pkgname} in chroot: ${chroot}"
          sudo libremakepkg -n ${chroot}

          pkgs+=( $(ls ${pkgname}-${pkgver}-${pkgrel}-${arch}.pkg.tar.zst 2> /dev/null) )
      done

      if   (( ${#pkgs[*]} ))
      then all_pkgs+=( ${pkgs[*]} )
           commit_msg+="[$(basename ${pkg_dir})]"
      else echo "ERROR: ${pkg_dir} - no packages generated"
      fi
  done

  if   (( ${#all_pkgs[*]} ))
  then git commit -m "${commit_msg}: rebuild against latest kernels" ${PKGBUILDS[*]}
  fi
  echo "(${#all_pkgs[*]}) packages generated" ; printf "%s\n" ${all_pkgs[*]} ;
}


if   git pull $ABS_UPSTREAM master &> /dev/null
then Main
else echo "failed to synchronize abslibre VCS - is the working tree dirty?"
fi
