#!/bin/bash
#
# pacstrap
#
# Copyright 2018, F123 Consulting, <information@f123.org>
# Copyright 2017, Mike Ray, <mike.ray@btinternet.com>
# Copyright 2018, Kyle, <kyle@free2.ml>
#
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3, or (at your option) any later
# version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this package; see the file COPYING.  If not, write to the Free
# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
#--code--

export TEXTDOMAIN=pacstrap
export TEXTDOMAINDIR=../locale
#export TEXTDOMAINDIR=/usr/local/share/locale

. gettext.sh

. ./functions


set -e

if ! check_root ; then
	PROGNAME=$0
	echo $(eval_gettext "Script must be run as root, try: sudo \$PROGNAME") ; echo
	exit 1
fi

cache=
directory=0
packagelist=

while getopts ':c:dhl:' flag
do
case $flag in
c)
	cache="--cachedir=$OPTARG"
;;
d)
directory=1
;;
h)
usage
exit 0
;;
l)
packagelist=$OPTARG
;;
:)
msg=$(gettext "Option requires an argument")
die '%s: %s -- '\''%s'\' "${0##*/}" "${msg}" "$OPTARG"
;;
?)
msg=$(gettext "Invalid option")
die '%s: %s -- '\''%s'\' "${0##*/}" "${msg}" "$OPTARG"
;;
esac
done

shift $(( OPTIND - 1 ))

(( $# )) || die "No root directory specified"

newroot=$1; shift

[[ -z "${packagelist}" ]] && die "No package list supplied"
[[ -f "${packagelist}" ]] || die "Package list ${packagelist} does not exist"
[[ -r "${packagelist}" ]] || die "Package list ${packagelist} is not readable"


mapfile -t softwareList < <(sed -e 's/\([[:space:]a-zA-Z0-9_.\+-]*\).*/\1/g' -e 's/^ *//' -e 's/ .*//' -e '/\(^\s*[[:punct:]]\|^$\)/d' "$packagelist")

[[ -d $newroot ]] || die "%s is not a directory" "$newroot"
if ! mountpoint -q "${newroot}" && (( ! directory )); then
die '%s is not a mountpoint!' "$newroot"
fi

if (( directory )) ; then
echo "Pacstrapping in ${newroot} directory"
	optiond='-d'
else
echo "Pacstrapping in ${newroot} mount-point"
fi

pacstrap -C ../pacman/pacman.rpi.conf ${optiond} "${newroot}" $cache --needed --noprogressbar "${softwareList[@]}"


echo done

exit 0

