#!/bin/bash

export TERM=linux

systemctl stop getty@tty1.service

# WICHTIG: feste Bindung an tty1 für dialog
exec </dev/tty1 >/dev/tty1 2>&1


echo "TERM=$TERM" > /tmp/snuk-firstboot.log
echo "TTY=$(tty)" >> /tmp/snuk-firstboot.log

DONEFILE="/etc/snukware-firstboot.done"

[ -f "$DONEFILE" ] && exit 0

# Nur auf echter Konsole laufen
[ -t 0 ] || exit 0

# Sprache
LANG_TMP=$(mktemp)

dialog \
  --title "Welcome to Snukware" \
  --msgbox "Welcome to Snukware First Boot Setup.\n\nPress OK to continue." \
  10 60

dialog \
  --title "Snukware Setup" \
  --menu "Select Language" \
  15 60 5 \
  "en_US.UTF-8" "English" \
  "en_GB.UTF-8" "English (UK)" \
  "de_DE.UTF-8" "Deutsch" \
  "fr_FR.UTF-8" "Francais" \
  "es_ES.UTF-8" "Espanol" \
  2>"$LANG_TMP"

LANGUAGE=$(cat "$LANG_TMP")
rm -f "$LANG_TMP"

[ -z "$LANGUAGE" ] && LANGUAGE="en_US.UTF-8"

# Tastatur
KEY_TMP=$(mktemp)

dialog \
  --title "Snukware Setup" \
  --menu "Select Keyboard Layout" \
  15 60 5 \
  "us" "US English" \
  "uk" "British English" \
  "de" "German" \
  "fr" "French" \
  "es" "Spanish" \
  2>"$KEY_TMP"

KEYMAP=$(cat "$KEY_TMP")
rm -f "$KEY_TMP"

[ -z "$KEYMAP" ] && KEYMAP="us"

# Zeitzone
TZ_TMP=$(mktemp)

dialog \
  --title "Snukware Setup" \
  --menu "Select Timezone" \
  20 70 10 \
  "UTC" "Universal Time" \
  "Europe/Berlin" "Germany" \
  "Europe/London" "United Kingdom" \
  "Europe/Paris" "France" \
  "America/New_York" "US East Coast" \
  "America/Chicago" "US Central" \
  "America/Denver" "US Mountain" \
  "America/Los_Angeles" "US West Coast" \
  2>"$TZ_TMP"

TIMEZONE=$(cat "$TZ_TMP")
rm -f "$TZ_TMP"

[ -z "$TIMEZONE" ] && TIMEZONE="UTC"

while true; do

    HOST_TMP=$(mktemp)

    dialog \
        --title "Snukware Setup" \
        --inputbox "Enter hostname:" \
        10 50 \
        "snukware" \
        2>"$HOST_TMP"

    RET=$?

    HOSTNAME=$(cat "$HOST_TMP")
    rm -f "$HOST_TMP"

    # Benutzer hat Cancel gedrückt
    [ $RET -ne 0 ] && HOSTNAME="snukware" && break

    # Leer -> Standard verwenden
    [ -z "$HOSTNAME" ] && HOSTNAME="snukware"

    # Hostname validieren
    if [[ "$HOSTNAME" =~ ^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$ ]]; then
        break
    fi

    dialog \
        --title "Invalid Hostname" \
        --msgbox \
        "Hostname may only contain letters,\nnumbers and hyphens.\n\nExample:\nsnukbox\nserver01\nlaptop-work" \
        12 50

done

# Konfiguration schreiben
cat > /etc/locale.conf <<EOF
LANG=$LANGUAGE
EOF

cat > /etc/vconsole.conf <<EOF
KEYMAP=$KEYMAP
EOF

ln -sf "/usr/share/zoneinfo/$TIMEZONE" /etc/localtime

hostnamectl set-hostname "$HOSTNAME"

dialog \
  --title "Snukware Setup" \
  --msgbox "Configuration saved.\n\nLanguage: $LANGUAGE\nKeyboard: $KEYMAP\nTimezone: $TIMEZONE\nHostname: $HOSTNAME" \
  10 60

touch "$DONEFILE"

systemctl disable snukware-firstboot.service >/dev/null 2>&1

clear

touch /etc/snukware-firstboot.done
systemctl start getty@tty1.service
exit 0
