#!/bin/bash
#
# config-base
#
# 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=config-base
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

[ -z "${HOSTNAME_}" ] && HOSTNAME_=alarmpi
[ -z "${ROOTPWD}" ] && ROOTPWD=root
[ -z "${USERNAME}" ] && USERNAME=alarm
[ -z "${USERPWD}" ] && USERPWD=alarm


directory=0


while getopts ':adhl:o:p:r:u:' flag
do
case $flag in
d)
directory=1
;;
h)
usage
exit 0
;;
l)
locale=${OPTARG}
;;
o)
HOSTNAME_=${OPTARG}
;;
p)
USERPWD=${OPTARG}
;;
r)
ROOTPWD=${OPTARG}
;;
u)
USERNAME=${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

[[ -d $newroot ]] || die "%s is not a directory" "$newroot"

# set the host name
input="echo \"${HOSTNAME_}\" > /etc/hostname"
echo "${input}"
chroot "${newroot}" /bin/bash -c "${input}"

# add root partition mount info to /etc/fstab
chroot "${newroot}" /bin/bash -c 'echo -e "\n\n/dev/mmcblk0p1  /boot   vfat    defaults        0       0\n\n" >> /etc/fstab'

set_password "${newroot}" root "${ROOTPWD}"

# Copy all modified files into the new system
cp -R ../files/* "${newroot}"

# Set the system locale
test -z $locale || set_locale "${newroot}" "${locale}"

# Add the regular user
add_user "${newroot}" "${USERNAME}"
set_password "${newroot}" "${USERNAME}" "${USERPWD}"
