#!/bin/bash

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

. ../etc/server.conf
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
  # Generate new host keys so every user gets unique keys
  rm /etc/ssh/ssh_host_rsa_key
  ssh-keygen -f /etc/ssh/ssh_host_rsa_key -N '' -t rsa
  rm /etc/ssh/ssh_host_dsa_key
  ssh-keygen -f /etc/ssh/ssh_host_dsa_key -N '' -t dsa
  rm /etc/ssh/ssh_host_ecdsa_key
  ssh-keygen -f /etc/ssh/ssh_host_ecdsa_key -N '' -t ecdsa
  rm /etc/ssh/ssh_host_ed25519_key
  ssh-keygen -f /etc/ssh/ssh_host_ed25519_key -N '' -t ed25519

    # Get the starting offset of the root partition
  PART_START=$(/sbin/parted /dev/mmcblk0 -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 /dev/mmcblk0 <<EOF
p
d
2
n
p
2
$PART_START

p
w
EOF
  /sbin/partprobe
  /bin/rm /usr/local/Repetier-Setup/etc/needExpandFS
  /sbin/resize2fs /dev/mmcblk0p2
fi

# Create new ssl certificate

make-ssl-cert generate-default-snakeoil --force-overwrite
