#! /bin/bash

# Set globals
LIBDIR=/usr/share/manjaro-arm-tools/lib
ARCH="aarch64"

# Import the library
source $LIBDIR/functions.sh 
enable_colors

# Check for root
check_root

# Check is the script already running
check_running

create_rootfs () {
    # Remove old rootfs if it exists
    if [ -d $BUILDDIR/$ARCH ]; then
        echo "Removing old rootfs..."
        rm -rf $BUILDDIR/$ARCH
    fi

    # Perform basic rootfs initialization
    msg "Creating rootfs..."
    mkdir -p $BUILDDIR/$ARCH/etc
    ln -s ../usr/lib/os-release $BUILDDIR/$ARCH/etc/os-release
    $LIBDIR/pacstrap -G -M -C $LIBDIR/pacman.conf.$ARCH $BUILDDIR/$ARCH pacman

    # Enable cross-architecture chrooting
    cp -a /usr/bin/qemu-aarch64-static $BUILDDIR/$ARCH/usr/bin
    
    # Fix SSL in the rootfs
    $NSPAWN $BUILDDIR/$ARCH update-ca-trust
    
    rm -f $BUILDDIR/$ARCH/var/cache/pacman/pkg/*
    $NSPAWN $BUILDDIR/$ARCH pacman-mirrors -f5 > /dev/null 2>&1
}

compress_rootfs () {
    msg "Compressing rootfs..."
    cd $BUILDDIR/$ARCH
    tar -czf $IMGDIR/Manjaro-ARM-$ARCH-latest.tar.gz .
    rm -rf $BUILDDIR/$ARCH
}

# Available options
opt=":a:h"

while getopts "${opt}" arg; do
  case $arg in
    a)
      ARCH="${OPTARG}"
      ;;
    \?)
      echo "Invalid option: -${OPTARG}"
      exit 1
      ;;
    h|?)
      echo "-h <help>       This help"
      exit 1
      ;;
    :)
      echo "Option -${OPTARG} requires an argument, aborting"
      exit 1
      ;;
  esac
done

# Log file
mkdir -p /var/log/manjaro-arm-tools
LOGFILE="/var/log/manjaro-arm-tools/buildrootfs-$(date +%Y-%m-%d-%H:%M).log"

# Commands
create_rootfs 2>&1 | tee --append "$LOGFILE"
compress_rootfs 2>&1 | tee --append "$LOGFILE"

# EOF
