#! /bin/bash

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

# 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:f:nxh"

while getopts "${opt}" arg; do
  case $arg in
    e)
      EDITION="${OPTARG}"
      ;;
    d)
      DEVICE="${OPTARG}"
      ;;
    v)
      VERSION="${OPTARG}"
      ;;
    n)
      KEEPROOTFS=false
      ;;
    x)
      EXTRACTED=true
      ;;
    i)
      ADD_PACKAGES="${OPTARG}"
      check_local_pkgs
      ;;
    f)
      FLASHVERSION="${OPTARG}"
      ;;
    \?)
      echo "Invalid option: -${OPTARG}"
      exit 1
      ;;
    h|?)
      echo "Only works with existing images on OSDN.net"
      usage_build_emmcflasher
      exit 1
      ;;
    :)
      echo "Option -${OPTARG} requires an argument, aborting"
      exit 1
      ;;
  esac
done

enable_colors

if [ "x" == "x$VERSION" ]; then
  echo "-v [option] is required"
  exit
fi

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

if [ ! -d "$PROFILES/arm-profiles" ]; then
    getarmprofiles
fi

# Start the timer
timer_start=$(get_timer)

# Package lists
PKG_DEVICE=$(grep "^[^#;]" $PROFILES/arm-profiles/devices/$DEVICE | awk '{print $1}')
PKG_EDITION=$(grep "^[^#;]" $PROFILES/arm-profiles/editions/minimal | awk '{print $1}')
SRV_EDITION=$(grep "^[^#;]" $PROFILES/arm-profiles/services/minimal | awk '{print $1}')
cat $PROFILES/arm-profiles/services/minimal | sed -e '/^#/d' > $SERVICES_LIST

# Create the rootfs used for the image
create_emmc_install
create_img
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
fi
prune_cache

# Show the timer
show_elapsed_time "${timer_start}"

# EOF
