#!/bin/sh

# post_install_rasp.sh
# 2023-10-14
# by Gernot Walzl

# Configure a fresh installation of Raspbian Linux.


EDITOR=${EDITOR:-nano}


config_raspi () {
  local TOOL
  TOOL=$(whiptail \
    --title "Configure Raspbian" \
    --menu "Which tool do you want to use for configuration?" \
    20 70 12 \
    1 "raspi-config" \
    2 "rc_gui  (X server required)" \
    3>&1 1>&2 2>&3)
  if [ $? -eq 0 ]; then
    case $TOOL in
      1) raspi-config ;;
      2) rc_gui ;;
    esac
  fi
}


edit_config () {
  whiptail \
    --title "Edit /boot/config.txt" \
    --msgbox "# uncomment to force a specific HDMI mode (this will force VGA)
hdmi_group=1
hdmi_mode=4   # 1280x720 60Hz 16:9  (increases the font size)
#..." \
    10 76
  $EDITOR /boot/config.txt
}


sync_clock () {
  local TIMEZONE="$(date +'%:z')"
  local DATETIME="$(date +'%Y-%m-%d %H:%M')"
  whiptail \
    --title "Clock" \
    --yesno "            Time Zone: $TIMEZONE
Date & Time (in zone): $DATETIME

Should ntpdate be installed to sync the clock?" \
  10 50 \
  --defaultno
  if [ $? -eq 0 ]; then
    killall ntpd
    apt-get install ntpdate
    ntpdate pool.ntp.org
  fi
}


upgrade_packages () {
  apt-get update
  apt-get dist-upgrade
}


install_auto_upgrade () {
  apt-get install anacron

  cat > '/etc/cron.daily/apt-get_upgrade' <<EOF
#!/bin/sh
apt-get update -y \\
  && apt-get upgrade -y
EOF
  chmod +x '/etc/cron.daily/apt-get_upgrade'
}


update_firmware () {
  BRANCH='stable' rpi-update
}


config_mime_xterm_omxplayer () {
  apt-get install xterm

  cat > '/usr/share/applications/xterm_omxplayer.desktop' <<EOF
[Desktop Entry]
Type=Application
Name=xterm_omxplayer
Exec=xterm -fullscreen -e omxplayer --blank %f
Categories=Other;
NoDisplay=true
MimeType=video/x-matroska;video/mp4;video/x-msvideo;video/x-flv;
Terminal=false
EOF

  cat > '/home/pi/.config/mimeapps.list' <<EOF
[Added Associations]
video/x-matroska=xterm_omxplayer.desktop;
video/mp4=xterm_omxplayer.desktop;
video/x-msvideo=xterm_omxplayer.desktop;
video/x-flv=xterm_omxplayer.desktop;

[Default Applications]
video/x-matroska=xterm_omxplayer.desktop
video/mp4=xterm_omxplayer.desktop
video/x-msvideo=xterm_omxplayer.desktop
video/x-flv=xterm_omxplayer.desktop
EOF
  chown pi:pi '/home/pi/.config/mimeapps.list'
}


add_repositories () {
  local VERSION_CODENAME=$(sed -n 's/^VERSION_CODENAME=//p' /etc/os-release)
  local REPOS
  REPOS=$(whiptail \
    --title "Add repositories" \
    --checklist "Which repositories do you want to add?" \
    20 70 12 \
    "gernot-walzl" on \
    --noitem \
    --separate-output \
    3>&1 1>&2 2>&3)
  if [ ! -z "$REPOS" ]; then
    for REPO in $REPOS; do
      case "$REPO" in
        'gernot-walzl')
          if [ "$(dpkg --print-architecture)" = "arm64" ]; then
            cat > '/etc/apt/sources.list.d/gernot-walzl.list' <<EOF
deb [ arch=arm64 ] http://gernot-walzl.at/Debian/Packages/ $VERSION_CODENAME main
EOF
          else
            cat > '/etc/apt/sources.list.d/gernot-walzl.list' <<EOF
deb [ arch=armhf ] http://gernot-walzl.at/Debian/Raspbian/Packages/ $VERSION_CODENAME main
EOF
          fi
          wget -O /etc/apt/trusted.gpg.d/gernot-walzl.asc \
            https://gernot-walzl.at/About/GPG-KEY
          ;;
      esac
    done
    apt-get update
  fi
}


disable_microsoft_repository () {
  local APT_SRC_DIR="/etc/apt/sources.list.d"
  if [ -f "${APT_SRC_DIR}/vscode.list" ]; then
    mv "${APT_SRC_DIR}/vscode.list" "${APT_SRC_DIR}/vscode.list.disabled"
    apt-get update
  fi
}


install_firewall () {
  if [ ! -f /etc/nftables.conf.orig ]; then
    mv /etc/nftables.conf /etc/nftables.conf.orig
  fi
  wget -O /etc/nftables.conf \
    https://gernot-walzl.at/Debian/Netfilter/nftables.conf
  chmod 750 /etc/nftables.conf
  systemctl enable nftables.service
}


install_additional_packages () {
  local PKGS
  PKGS=$(whiptail \
    --title "Install additional software" \
    --checklist "Which packages do you want to install?" \
    20 70 12 \
    "emacs" on \
    "geeqie" on \
    "qpdfview" on \
    "audacious" on \
    "vlc" on \
    "synaptic" on \
    "build-essential" on \
    "debsums" on \
    "xscreensaver" off \
    "webext-ublock-origin-chromium" on \
    "blueman" off \
    "pysolfc" off \
    "frozen-bubble" off \
    "pingus" off \
    "warmux" off \
    --noitem \
    --separate-output \
    3>&1 1>&2 2>&3)
  if [ ! -z "$PKGS" ]; then
    for PKG in $PKGS; do
      echo
      echo "apt-get install $PKG"
      echo
      apt-get install "$PKG"
    done
  fi
}


edit_inputrc () {
  whiptail \
    --title "Edit /etc/inputrc" \
    --msgbox "# alternate mappings for \"page up\" and \"page down\" to search the history
\"\e[5~\": history-search-backward
\"\e[6~\": history-search-forward" \
    10 76
  $EDITOR /etc/inputrc
}


dynamic_motd () {
  local URL="https://gernot-walzl.at/Debian/motd"
  cd /etc/update-motd.d || return 1
  wget -O 50-sysinfo "$URL/50-sysinfo"
  chmod +x 50-sysinfo
  wget -O 98-reboot-required "$URL/98-reboot-required"
  chmod +x 98-reboot-required
}


config_dns () {
  cat > '/etc/resolv.conf.head' <<EOF
nameserver 8.8.8.8
EOF
}


fix_sound_pulse () {
  if ! dpkg -s pulseaudio; then
    return 1
  fi

  # https://www.raspberrypi.org/forums/viewtopic.php?t=251455
  whiptail \
    --title "Edit /usr/share/pulseaudio/alsa-mixer/profile-sets/default.conf" \
    --msgbox "# Enable stereo by commenting out mono
;[Mapping analog-mono]
;device-strings = hw:%f
;channel-map = mono
;paths-output = analog-output analog-output-lineout analog-output-speaker analog-output-headphones analog-output-headphones-2 analog-output-mono
;paths-input = analog-input-front-mic analog-input-rear-mic analog-input-internal-mic analog-input-dock-mic analog-input analog-input-mic analog-input-linein analog-input-aux analog-input-video analog-input-tvtuner analog-input-fm analog-input-mic-line analog-input-headset-mic
;priority = 7" \
    16 76
  $EDITOR /usr/share/pulseaudio/alsa-mixer/profile-sets/default.conf

  # https://steamcommunity.com/app/353380/discussions/6/1642042464753800526/
  whiptail \
    --title "Edit /etc/pulse/default.pa" \
    --msgbox "# tsched=0 fixes poor audio quality (stuttering, crackling)
load-module module-udev-detect tsched=0" \
    16 76
  $EDITOR /etc/pulse/default.pa
}


while :; do
  SELECTED=1
  if [ "$FUN" != "" ]; then
    SELECTED=$(($FUN + 1))
  fi
  FUN=$(whiptail --title "Configure Raspbian" \
    --menu "Welcome to the post installation script of Raspbian Linux.
Please choose an option:" \
    --default-item "$SELECTED" 20 70 10 \
    1 "config_raspi" \
    2 "edit_config" \
    3 "sync_clock" \
    4 "upgrade_packages" \
    5 "install_auto_upgrade" \
    6 "add_repositories" \
    7 "disable_microsoft_repository" \
    8 "install_firewall" \
    9 "install_additional_packages" \
    10 "edit_inputrc" \
    11 "dynamic_motd" \
    12 "config_dns" \
    13 "fix_sound_pulse" \
    3>&1 1>&2 2>&3)
  RET=$?
  if [ $RET -eq 0 ]; then
    case $FUN in
      1) config_raspi ;;
      2) edit_config ;;
      3) sync_clock ;;
      4) upgrade_packages ;;
      5) install_auto_upgrade ;;
      6) add_repositories ;;
      7) disable_microsoft_repository ;;
      8) install_firewall ;;
      9) install_additional_packages ;;
      10) edit_inputrc ;;
      11) dynamic_motd ;;
      12) config_dns ;;
      13) fix_sound_pulse ;;
      *) break
    esac
  else
    break
  fi
  echo
  echo "Press Enter to continue."
  read CONTINUE
done