#!/bin/bash
#
# Copyright 2018, F123 Consulting, <information@f123.org>
# Copyright 2018, Kyle, <kyle@free2.ml>
# Copyright 2019, Storm Dragon, <stormdragon2976@gmail.com>
#
# 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--

# the gettext essentials
export TEXTDOMAIN=build-f123light
export TEXTDOMAINDIR=/usr/share/locale

. gettext.sh

# This is the name by which the script is called,minus the path
# Gettext doesn't like the parameter or the basename command substitution.
name=${0##*/}

# Log writing function
log() {
    while read -r line ; do
        echo "$line" | sudo tee -a "$logFile" &> /dev/null
    done
}
                                                                                                                                                                
# Log file name is /var/log/scriptname
logFile="/var/log/${0##*/}"
# Clear previous logs
echo -n | sudo tee "$logFile" &> /dev/null
                                                                                                                                                                
  
set -o pipefail
# Defaults
branch=master

declare -A argList=(
	[b:]="branch:,"
	[d:]="work-directory:,"
	[H:]="hostname:,"
	[h]="help,"
	[n:]="network-name:,"
	[o:]="output-file:,"
	[p:]="password:,"
	[r:]="root-password:,"
	[s:]="size:,"
	[u:]="user:,"
	[w:]="wifi-password:"
)

short="${!argList[*]}"
short="${short// /}"
long="${argList[*]}"
long="${long// /}"


# Get command line options
if ! options=$(getopt -o $short -l $long -n "build-f123light" -- "$@" |& log); then
	echo "Options were not passed" | log
	exit 1
fi

eval set -- "$options"

# Create the args array and strip off the branch
declare -a args
while [[ $# -gt 0 ]]; do
	if [[ "$1"  == "-b" || "$1" == "--branch" ]]; then
		echo "Set $1 $2 as branch, removed from argument list" | log
		shift
		shift
	fi
	if [[ -n "$1" ]]; then
		echo "Added $1 to args array." | log
		args+=($1)
	fi
done

# If all is good, call here with $@ as parameters.
[[ -d /tmp/F123Light/ ]] && rm -rfv /tmp/F123Light |& log
# clone  the git repository.
git clone -b $branch --depth 1 https://gitlab.com/f123/F123Light.git /tmp/F123Light |& git
# build the image
/echo "Calling tmp/F123Light/build/build.sh ${args[@]}" | log
/tmp/F123Light/build/build.sh ${args[@]}

exit 0
