#!/bin/bash
set -e
set -x
echo 'initial configuration'
# Parse the JSON file
while IFS="=" read -r key value; do
  declare "$key=$value"
done < <(jq -r 'to_entries|map("\(.key)=\(.value|tostring)")|.[]' config.json)

echo "$hostname" > /etc/hostname
echo "127.0.0.1 $hostname"> /etc/hosts

echo "$timezone" > /etc/timezone
ln -sf /usr/share/zoneinfo/America/Los_Angeles /etc/localtime

# Set the root password
echo "root:$root_password" | chpasswd

#set additional profile options.
jq --compact-output -r '.profile[]' config.json | while read -r line; do
  echo "$line" >> /etc/profile
done

echo "export PATH=$PATH:/usr/local/go/bin" >> /etc/profile

#set default shell to bash.
sed -i 's|^SHELL=.*|SHELL=/bin/bash|' /etc/default/useradd

user_mod() {
  echo "$1"
  username=$(echo "$1" | jq -r '.username')
  password=$(echo "$1" | jq -r '.password')

  # Create user
  if getent passwd "$username" >/dev/null 2>&1; then
    echo "User already exists"
  else
    useradd -m "$username"
  fi   

  # Set password
  echo "$username:$password" | chpasswd

  # Add to sudo group
  usermod -aG sudo "$username"
}
jq --compact-output -r '.users[]' config.json | while read -r line; do
  user_mod "$line"
done
echo "Configuration applied."

rm /config.json
rm /apply_initial_host_configuration.sh
rm /filesystem_chroot_install.sh
