#!/bin/bash

# Configuration variables
LIBDIR='/usr/share/manjaro-arm-tools/lib'
KEEPROOTFS='true'
EXTRACTED='false'
FACTORY='false'
BMAP='false'
CUSTOM_REPO=

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

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

# Check for root
check_root

# Check is the script already running
check_running

# Available options
opt=":e:d:v:i:b:nfxhk:mos:p:cz:"

while getopts "${opt}" arg; do
  case $arg in
    c)
      COLORS='true'
      ;;
    e)
      EDITION="${OPTARG}"
      ;;
    d)
      DEVICE="${OPTARG}"
      ;;
    v)
      VERSION="${OPTARG}"
      ;;
    n)
      KEEPROOTFS='false'
      ;;
    x)
      EXTRACTED='true'
      ;;
    i)
      ADD_PACKAGES="${OPTARG}"
      check_local_pkgs
      ;;
    b)
      BRANCH="${OPTARG}"
      ;;
    f)
      FACTORY='true'
      ;;
    m)
      BMAP='true'
     ;;
    k)
      CUSTOM_REPO="${OPTARG}"
     ;;
    s)
      HOSTNAME="${OPTARG}"
     ;;
    p)
      FILESYSTEM="${OPTARG}"
      ;;
    z)
      COMPRESSION="${OPTARG}"
      ;;
    \?)
      echo "Option -${OPTARG} is not valid, aborting"
      exit 1
      ;;
    h|?)
      usage_build_img
      exit 1
      ;;
    :)
      echo "Option -${OPTARG} requires an argument, aborting"
      exit 1
      ;;
  esac
done

[[ "$COLORS" = "true" ]] && enable_colors

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

IMGNAME="Manjaro-ARM-$EDITION-$DEVICE-$VERSION"
ARCH='aarch64'

if [ ! -d "$PROFILES/arm-profiles" ]; then
    getarmprofiles 2>&1 | tee --append "$LOGFILE"
fi

# Make sure only a known branch is used
check_branch

# Start the timer
timer_start=$(get_timer)

# Package lists
PKG_DEVICE=$(grep "^[^#;]" $PROFILES/arm-profiles/devices/$DEVICE | awk '{print $1}')
PKG_SHARED=$(grep "^[^#;]" $PROFILES/arm-profiles/editions/shared | sed -e 's/>'${DEVICE//pro/}' //' -e '/^>/d' -e 's/#.*//')
PKG_EDITION=$(grep "^[^#;]" $PROFILES/arm-profiles/editions/$EDITION | sed -e 's/>'${DEVICE//pro/}' //' -e '/^>/d' -e 's/#.*//')
cat $PROFILES/arm-profiles/services/$EDITION \
    | sed -e '/^#/d' -e 's/>'${DEVICE//pro/}' //' -e '/^>/d' -e 's/#.*//' \
    > $SERVICES_LIST

# Create the rootfs used for the image
create_rootfs_img 2>&1 | tee --append "$LOGFILE"

case "$DEVICE" in
    halium-9)
        create_img_halium 2>&1 | tee --append "$LOGFILE"
        ;;
    *)
        create_img 2>&1 | tee --append "$LOGFILE"
        ;;
esac

if [ $BMAP = true ]; then
    create_bmap 2>&1 | tee --append "$LOGFILE"
fi

if [[ "$EXTRACTED" = "true" ]]; then
    info "Image not compressed, option -x was passed"
else
    # Create the compressed file from the .img file that will be deleted
    compress 2>&1 | tee --append "$LOGFILE"
fi

# Show the timer
show_elapsed_time "${timer_start}" 2>&1 | tee --append "$LOGFILE"

# EOF
