#!/bin/bash

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$DIR" || exit

REBOOT=0

# . /boot/repetier-image-setup.txt
. ../etc/server.conf
if [ -f "/boot/firmware/repetier-network.conf" ]; then
    . /boot/firmware/repetier-network.conf
fi
export LC_ALL=C

# Turn power management of wlan off
/sbin/iwconfig "$WLAN" power off

# Set wifi channels to regulatory of selected country
iw reg set "$COUNTRY"

if [ -e "/usr/local/Repetier-Setup/etc/needExpandFS" ]; then
  ROOT_PART="$(findmnt / -o source -n)"
  ROOT_DEV="/dev/$(lsblk -no pkname "$ROOT_PART")"
  fdisk -l | grep "Disk $ROOT_DEV"
  # shellcheck disable=SC2181
  if [ "$?" -eq "0" ]; then
    PART_NUM="$(echo "$ROOT_PART" | grep -o "[[:digit:]]*$")"
    LAST_PART_NUM=$(parted "$ROOT_DEV" -ms unit s p | tail -n 1 | cut -f 1 -d:)
    if [ "$LAST_PART_NUM" -eq "$PART_NUM" ]; then
      # Get the starting offset of the root partition
      PART_START=$(/sbin/parted "$ROOT_DEV" -ms unit s p | /bin/grep "^2:" | /usr/bin/cut -f 2 -d: | /bin/sed -e 's/s//g')
      [ "$PART_START" ] || return 1
      # Return value will likely be error for fdisk as it fails to reload the
      # partition table because the root fs is mounted
      /sbin/fdisk "$ROOT_DEV" <<EOF
p
d
$PART_NUM
n
p
$PART_NUM
$PART_START

p
w
EOF
      # /sbin/partprobe
      # /sbin/resize2fs /dev/mmcblk0p2
      cat <<EOF >/etc/init.d/resize2fs_once &&
#!/bin/sh
### BEGIN INIT INFO
# Provides: resize2fs_once
# Required-Start:
# Required-Stop:
# Default-Start: 3
# Default-Stop:
# Short-Description: Resize the root filesystem to fill partition
# Description:
### END INIT INFO

. /lib/lsb/init-functions

case "\$1" in
    start)
      log_daemon_msg "Starting resize2fs_once" &&
      resize2fs "$ROOT_PART" &&
      update-rc.d resize2fs_once remove &&
      rm /etc/init.d/resize2fs_once &&
      log_end_msg \$?
      ;;
    *)
      echo "Usage: \$0 start" >&2
      exit 3
      ;;
esac
EOF
      chmod +x /etc/init.d/resize2fs_once
      update-rc.d resize2fs_once defaults
    fi
  fi
  # Generate new host keys so every user gets unique keys
  rm /etc/ssh/ssh_host_*
  ssh-keygen -A
  # Create new ssl certificate

  make-ssl-cert generate-default-snakeoil --force-overwrite
  cp /etc/ssl/certs/ssl-cert-snakeoil.pem /etc/haproxy/combined.pem
  cat /etc/ssl/private/ssl-cert-snakeoil.key >> /etc/haproxy/combined.pem
  /bin/rm /usr/local/Repetier-Setup/etc/needExpandFS
  REBOOT=1
fi

# Switch to armel version if we are on pi zero or pi 1
< /proc/cpuinfo grep ARMv6 >/dev/null
IS_V6=$?
if [[ -f "/usr/local/Repetier-Setup/server/server-arm-el.deb" ]] && [ "$IS_V6" == "0" ]; then
  # Disable x server
  systemctl --quiet set-default multi-user.target
  rm -f /etc/systemd/system/getty@tty1.service.d/autologin.conf
  # Install alternative server
  dpkg -i /usr/local/Repetier-Setup/server/server-arm-el.deb
  mv /usr/local/Repetier-Setup/server/server-arm-el.deb /usr/local/Repetier-Setup/server/server-arm-el.deb_installed
fi

# Check for manual wifi configuration

# user might have changed country so set on boot
iw reg set "$COUNTRY"

# Set current hotspot settings in case file was changed
nmcli --terse connection show | cut -d : -f 1 |
            while read name; do
                if [[ "$name" == "Hotspot" ]] ; then
                    /usr/local/Repetier-Setup/bin/manageWifiAccess ap
                fi
            done

if [ -f "/boot/firmware/ManualWifi.conf" ]; then
  # First activation?
  if [ ! -f "/etc/NetworkManager/system-connections/manual.nmconnection" ]; then
    /usr/local/Repetier-Setup/bin/manageWifiAccess activateManualControl
  fi
  # File changed? Then reactivate
  if ! cmp /boot/firmware/ManualWifi.conf /etc/NetworkManager/system-connections/manual.nmconnection >/dev/null 2>&1; then
    /usr/local/Repetier-Setup/bin/manageWifiAccess activateManualControl
  fi
fi

if [ "$REBOOT" == "1" ]; then
  echo "Reboot to activate ssh"
  reboot
fi
