#!/bin/bash

TIMEZONE="Europe/Paris"
ROOTPWD="admin"

target="$(cat  /etc/rootcfg/target  2>/dev/null | xargs)"
device="$(cat  /etc/rootcfg/device  2>/dev/null | xargs)"
ddrsize="$(cat /etc/rootcfg/ddrsize 2>/dev/null | xargs)"
setup="$(cat   /etc/rootcfg/setup   2>/dev/null | xargs)"
brlanip="$(cat /etc/rootcfg/brlanip 2>/dev/null | xargs)"

if [ -z "${target}" ] || [ -z "${device}" ]; then
  rootdev="$(lsblk -pilno name,type,mountpoint | grep -G 'part /$' | head -n1 | cut -d" " -f1)"
  if [ -n "${rootdev}" ]; then
    partlabelroot=$(blkid "${rootdev}" -s PARTLABEL -o value)
    if [ -n "${partlabelroot}" ]; then
      target=$(echo "${partlabelroot}" | cut -d'-' -f1)
      device=$(echo "${partlabelroot}" | cut -d'-' -f2)
    fi
  fi
fi

function cannotchange() {
  if   [[ -z "$1" ]]; then echo "$2"
  elif [[ -z "$2" ]]; then echo "$1"
  elif [[ "$1" == "$2" ]]; then echo "$1"
  else echo "Cannot change $1 to $2" >&2
  fi
}

while [ "${1:-}" != '' ]; do
  case "$1" in
  '-i' | '--brlanip')   shift;   brlanip="${1}"        ;;
         '--brlanip'=*)          brlanip="${1#*=}"     ;;
  '-d' | '--ddrsize')   shift;   ddrsize="${1}"        ;;
         '--ddrsize'=*)          ddrsize="${1#*=}"     ;;
  '-s' | '--setup')     shift;   setup="${1}"          ;;
         '--setup'=*)            setup="${1#*=}"       ;;
  '-t' | '--target')    shift;   target="$(cannotchange "${target}" "${1}")"    ;;
         '--target'=*)           target="$(cannotchange "${target}" "${1#*=}")" ;;
  '-a' | '--device')    shift;   device="$(cannotchange "${device}" "${1}")"    ;;
         '--device'=*)           device="$(cannotchange "${device}" "${1#*=}")" ;;
  '-u' | '--adduser')   shift;   adduser="${1}"        ;;
         '--adduser'=*)          adduser="${1#*=}"     ;;
  '-n' | '--noask')              noask=1               ;;
  '-m' | '--menuonly')           menuonly=1            ;;
  *) cat <<-EOF
	Usage: $(basename "$0") [OPTION]...
	  -i --brlanip [IP]                       specify ip for brlan
	  -d --ddrsize [default|8]                specify ddr size
	  -s --setup [AP|RT|...]                  specify setup for network
	  -t --target [bpir64|bpir3|bpir3m|bpir4] specify target
	     --device [sdmmc|emmc|nvme|sata]      specify device
	  -u --adduser [USER]      add user named USER
	  -n --noask               don't ask to alter rootfs and reset passwords and root access
	  -m --menuonly            menu only
	EOF
    exit 1
    ;;
  esac
  shift
done

[ -z "${target}" ] && exit 1
[ -z "${device}" ] && exit 1

case ${target} in
  bpir64)
    DDRSIZES=("default    1 GB")
    SETUPS=("RT       Router setup"
            "AP       Access Point setup")
    WIFIMODULE="mt7615e"
    ;;
  bpir3)
    DDRSIZES=("default    2 GB")
    SETUPS=("RT       Router setup, SFP module eth1 as wan"
            "RTnoSFP  Router setup, not using SFP module"
            "AP       Access Point setup")
    WIFIMODULE="mt7915e"
    ;;
  bpir3m)
    DDRSIZES=("default    2 GB")
    SETUPS=("RT       Router setup"
            "AP       Access Point setup")
    WIFIMODULE="mt7915e"
    ;;
  bpir4)
    DDRSIZES=("default    4 GB"
              "8          8 GB")
    SETUPS=("RTnoSFP  Router setup, not using SFP module, wan=lan0"
            "AP       Access Point setup")
    WIFIMODULE="mt7915e"
    ;;
  *)
    echo "Unknown target '${target}'"
    exit
    ;;
esac

function ask() {
  local a items count
  if [ -z "${!1}" ]; then
    eval 'items=("${'"${2}"'[@]}")'
    eval 'count=${#'"${2}"'[@]}'
    if [ ${count} -gt 1 ]; then
      PS3="${3} "; COLUMNS=1; echo
      select a in "${items[@]}" "Quit"; do
        (( REPLY > 0 && REPLY <= ${count} )) && break || exit 1
      done
    else
      a=${items[0]}
      echo -e "\n${3} $a"
    fi
    export declare $1=${a%% *}
  fi
}

if [ -n "$menuonly" ]; then
  ask ddrsize DDRSIZES "Choose the size of ddr ram:"
else
  [ -z "${ddrsize}" ] && ddrsize="default"
fi
echo "DDRsize=$ddrsize"
ask setup SETUPS "Choose setup to create root for:"
echo "Setup=$setup"
if [ -z "$brlanip" ]; then
  read -p "Enter ip address for local network (emtpy for default): " brlanip
  [ -z "$brlanip" ] && brlanip="default"
  echo "IP=$brlanip"
fi


if [ -n "$menuonly" ]; then
  mkdir -p /tmp/bpir-rootfs
  echo -n "${setup}"   > /tmp/bpir-rootfs/setup
  echo -n "${ddrsize}" > /tmp/bpir-rootfs/ddrsize
  echo -n "${brlanip}" > /tmp/bpir-rootfs/brlanip
  exit 0
elif [ -z "$noask" ]; then
  read -p "Type <yes> to alter your rootfs! " prompt
  [[ "${prompt}" != "yes" ]] && exit 1
fi

function setupMACconfig {
  file="/etc/systemd/network/mac.txt"
  while [ ! -z "$(cat $file 2>/dev/null | grep 'aa:bb:cc:dd:ee:ff')" ]; do
    mac_read="$(cat $file 2>/dev/null | grep -m1 'aa:bb:cc:dd:ee:ff' | cut -d ' ' -f1)"
    mac="${mac_read::17}"
    nr="${mac_read:18}"
    [ -z "$nr" ] && nr=1
    first="aa:bb:cc"
    while [ ! -z "$(cat "${file}" | grep "${mac}")" ]; do # make sure all macs are different
      mac=$first:$(printf %02x $(($RANDOM%256))):$(printf %02x $(($RANDOM%256)))
    done
    mac=${mac}:$(printf %02x $(($RANDOM%256)) )
    mac=${mac::-2}$(printf %02x $(((16#${mac: -2}&-$nr)+0)))
    sed -i '0,/aa:bb:cc:dd:ee:ff/{s/aa:bb:cc:dd:ee:ff/'${mac}'/}' "${file}"
  done
}

if [ ! -f "/etc/arch-release" ]; then ### Ubuntu / Debian
  sshd="ssh"
  wheel="sudo"
  groups="audio,games,lp,video,$wheel"
else # ArchLinuxArm
  sshd="sshd"
  wheel="wheel"
  groups="audio,games,log,lp,optical,power,scanner,storage,video,$wheel"
fi
sync
sed -i 's/\bdummy\b/PARTLABEL='${target}'-'${device}'-root/g' /etc/fstab
mkdir -p /etc/modules-load.d /etc/modprobe.d
echo -e "# Load ${WIFIMODULE}.ko at boot\n${WIFIMODULE}" | \
         tee /etc/modules-load.d/${WIFIMODULE}.conf
#  echo "options mt7915e wed_enable=Y" | \
#           tee /etc/modprobe.d/mt7915e.conf

if [ -n "$noask" ]; then
  echo "%${wheel} ALL=(ALL) ALL" | tee /etc/sudoers.d/wheel
  sed -i 's/.*PermitRootLogin.*/PermitRootLogin yes/' /etc/ssh/sshd_config
  sed -i 's/.*UsePAM.*/UsePAM no/' /etc/ssh/sshd_config
  ln -sf "/usr/share/zoneinfo/${TIMEZONE}" /etc/localtime
  echo root:$ROOTPWD | chpasswd
fi

if [ -n "${setup}" ]; then
  cp -rfvL "/usr/share/buildR64arch/etc" /
  wdir="/etc/systemd/network"; rm -rf "${wdir}/"*
  cp -rfvL "/usr/share/buildR64arch/network/${target^^}-${setup}/"* "${wdir}"
  wdir="/etc/hostapd";         rm -rf "${wdir}/"*
  cp -rfvL "/usr/share/buildR64arch/hostapd/${target^^}/"* "${wdir}"
  if [ -n "$brlanip" ] && [[ "${brlanip}" != "default" ]]; then
    sed -i 's/Address=.*/Address='${brlanip}'\/24/' /etc/systemd/network/10-brlan.network
  fi
  systemctl --force --no-pager reenable ${sshd}.service
  systemctl --force --no-pager reenable systemd-timesyncd.service
  systemctl --force --no-pager reenable systemd-resolved.service
  if [[ ${setup} == "RT"* ]]; then
    systemctl --force --no-pager reenable nftables.service
  else
    systemctl --force --no-pager disable nftables.service
  fi
  systemctl --force --no-pager reenable systemd-networkd.service
  find -L "/etc/hostapd" -name "*.conf"| while read conf ; do
    conf="$(basename "${conf}")"; conf="${conf/".conf"/""}"
    systemctl --force --no-pager reenable hostapd@${conf}.service 2>&1 \
             | grep -v "is added as a dependency to a non-existent unit"
  done
  setupMACconfig
fi

if [[ "${ddrsize}" == "default" ]] || [ -z "${ddrsize}" ]; then
  rm -f /boot/bootcfg/ddrsize 2>/dev/null
else
  echo -n "${ddrsize}" >/boot/bootcfg/ddrsize
fi

if [ -n "${adduser}" ]; then
  useradd --create-home --user-group --groups ${groups} -s /bin/bash "${adduser}"
  passwd "${adduser}"
fi

bpir-toolbox --create-parts --target="${target}" --device="${device}"
rm -f /etc/rootcfg/setup   2>/dev/null
rm -f /etc/rootcfg/brlanip 2>/dev/null
sync

