#!/usr/bin/env bash

set -e
PROG_NAME="$0"
ARGS="$@"
VERSION="4.14-1.20.1"


function print_version() {
    echo "Re4son Pi-TFT Setup $VERSION"
    exit 0
}

function update_autologon() {
    if [[ $EUID -ne 0 ]]; then
        bail "re4son-pi-tft-setup must be run as root. try: sudo re4son-pi-tft-setup"
    fi

    ## We'll always start with a clean slate, i.e. no autologon
    file="/etc/systemd/system/getty@tty1.service.d/override.conf"
    path=$(dirname "${file}")
    legacy_file="/etc/systemd/system/getty.target.wants/getty@tty1.service"
    info AUTOLOGON "Disabling autologon"
    if [ -f ${file} ]; then
        rm -f ${file}
    fi
    ## Disabling when enabled with verion <= 4.x-1.14.3
    sed -i 's/ExecStart=-\/sbin\/agetty -a .*%I\+/ExecStart=-\/sbin\/agetty --noclear %I/g' $legacy_file
    info AUTOLOGON "Autologon disabled!"
    ## systemd >233 breaks this so we have to re-enable the getty service
    if [ -f /etc/systemd/system/getty.target.wants/getty@tty1.service ]; then
        rm -f /etc/systemd/system/getty.target.wants/getty@tty1.service
    fi
    systemctl enable getty@tty1.service
    sed /etc/lightdm/lightdm.conf -i -e "s/^autologin-user=.*/#autologin-user=/" 

    ## Now we enable autologon if so desired
    if [ "${user_name}" != "disable" ]; then
        target=$(systemctl get-default)
        if [ "${target}" == "multi-user.target" ]; then 
            info AUTOLOGON "Enabling autologon for user $user_name"
            if [ ! -d ${path} ]; then
                mkdir -p ${path}
            fi
            cat >> ${file} <<EOF
# --- added by re4son-pi-tft-setup $date ---
# enable autologin
[Service]
ExecStart=
ExecStart=-/sbin/agetty -a $user_name --noclear %I $TERM
Type=idle
# --- end re4son-pi-tft-setup $date ---
EOF
        fi
        if [ "${target}" == "graphical.target" ]; then 
            info AUTOLOGON "Enabling autologon for user $user_name"
            sed /etc/lightdm/lightdm.conf -i -e "s/^\(#\|\)autologin-user=.*/autologin-user=$user_name/" 
        fi	
        info AUTOLOGON "Autologon enabled for user $user_name!"
    fi
}

function check_update() {
    if [[ $EUID -ne 0 ]]; then
        bail "re4son-pi-tft-setup must be run as root. try: sudo re4son-pi-tft-setup"
    fi
    TEMP_FILE="/tmp/re4son-pi-tft-setup"
    info UPDATE "Downloading update"
    wget -O ${TEMP_FILE} https://github.com/Re4son/Re4son-Pi-TFT-Setup/raw/rpts-4.14/re4son-pi-tft-setup
    cp $TEMP_FILE $PROG_NAME
    chmod +x $PROG_NAME
    rm -f $TEMP_FILE
    info UPDATE "Replaced old version:"
    echo "Re4son Pi-TFT Setup $VERSION"
    echo
    info UPDATE "With new version:"
    source "$PROG_NAME" -v
    exit 0
}

function remove_tft() {
    info UPDATE "Removing TFT configuration"
    rm -f /etc/X11/xorg.conf.d/99-fbdev.conf
    rm -f /etc/X11/xorg.conf.d/99-calibration.conf
    rm -f /etc/pointercal
    rm -f /dev/input/touchscreen
    rm -f /etc/udev/rules.d/95-*.rules
    if [ -e ${target_homedir}/99-fbturbo.conf ]; then
        mv ${target_homedir}/99-fbturbo.conf /usr/share/X11/xorg.conf.d/99-fbturbo.conf
    fi
    rm -f ${target_homedir}/99-fbdev.conf
    rm -f ~/99-fbdev.conf
    rm -f /etc/modprobe.d/re4son.conf
    rm -f /usr/share/X11/xorg.conf.d/45-evdev.conf
    sed -i 's/rootwait fbcon=map:10 fbcon=font:VGA8x8/rootwait/g' "/boot/cmdline.txt"
    sed -i 's/4dpi.rotate=180 rootwait/rootwait/g' "/boot/cmdline.txt"
    sed -i 's/BLANK_TIME=0/BLANK_TIME=10/g' "/etc/kbd/config"
    sed -i '/added by re4son-pi-tft-setup/,/end re4son-pi-tft-setup/d' "/boot/config.txt"
    sed -i '/added by re4son-pi-tft-setup/,/end re4son-pi-tft-setup/d' "/etc/modules"
    sed -i '/added by re4son-pi-tft-setup/,/end re4son-pi-tft-setup/d' "${target_homedir}/.profile"
    if [ -e ${target_homedir}/.60-libinput.conf.bak ]; then
        mv ${target_homedir}/.60-libinput.conf.bak /usr/share/X11/xorg.conf.d/60-libinput.conf
    fi
    info UPDATE "TFT config removed"
    echo
    read -p "Reboot to apply changes? (y/n): " -n 1 -r
    echo

    if [[ $REPLY =~ ^[Yy]$ ]]; then
       reboot
    fi
    exit 0
}

function print_help() {
    echo "Usage: $0 -t [pitfttype]"
    echo "    -h            Print this help"
    echo "    -v            Print version information"
    echo "    -a [user]     Enable autologon for [user], use [user] 'disable' to disable autologon"
    echo "    -b [bootpref] Set boot preference:"
    echo "                    'cli' for boot to command line"
    echo "                    'gui' for boot to desktop"
    echo "    -u            Update Re4son Pi-TFT Setup"
    echo "    -r            Remove TFT configuration (undo setup)"
    echo "    -d [dir]      Specify path of user's home directory to back up and restore some files (defaults to /home/pi)"
    echo "    -t [type]     Specify the type of TFT:"
    echo "                                             '28r'      (Adafruit 2.8\" resistive)"
    echo "                                             '28c'      (Adafruit 2.8\" capacitive)"
    echo "                                             '35r'      (Adafruit 3.5\")"
    echo "                                             '35ro'     (Adafruit 3.5\") Overclocked"
    echo "                                             '22'       (Adafruit 2.2\")"
    echo "                                             '4dpi'     (4D Systems 2.4\",3.2\" and 3.5\")"
    echo "                                             'elec22'   (Elecfreak 2.2\")"
    echo "                                             'hy28b'    (Hotmcu HY28B 2.8\")"
    echo "                                             'jb35'     (JBTek 3.5\")"
    echo "                                             'kum35'    (Kuman 3.5\")"
    echo "                                             'pi70'     (Raspberry Pi 7\")"
    echo "                                             'sain32'   (Sainsmart 3.2\")"
    echo "                                             'sain35'   (Sainsmart 3.5\")"
    echo "                                             'wave32'   (Waveshare 3.2\")"
    echo "                                             'wave35'   (Waveshare 3.5\" (a))"
    echo "                                             'wave35b'  (Waveshare 3.5\" (b))"
    echo "                                             'wave35o'  (Waveshare 3.5\" Overclocked)"
    echo "                                             'wave35h'  (Waveshare 3.5\" HDMI)"
    echo "                                             'wave35c'  (Waveshare 3.5\" Clones, such as:"
    echo "                                                                         Elecrow 3.5\""
    echo "                                                                         KeDei 3.5\""
    echo "                                                                         Osoyoo 3.5\")"
    echo "                                             'wave40'   (Waveshare 4\")"
    echo "                                             'wave50'   (Waveshare 5\" HDMI)"
    echo
    echo "You must specify a type of display. Try \"wave35c\" if you are unsure what to use."
    exit 1
}

group=RE4SON
function info() {
    system="$1"
    group="${system}"
    shift
    FG="1;32m"
    BG="40m"
    echo -e "[\033[${FG}\033[${BG}${system}\033[0m] $*"
}

function bail() {
    FG="1;31m"
    BG="40m"
    echo -en "[\033[${FG}\033[${BG}${group}\033[0m] "
    if [ -z "$1" ]; then
        echo "Exiting due to error"
    else
        echo "Exiting due to error: $*"
    fi
    exit 1
}

function ask() {
    # http://djm.me/ask
    while true; do

        if [ "${2:-}" = "Y" ]; then
            prompt="Y/n"
            default=Y
        elif [ "${2:-}" = "N" ]; then
            prompt="y/N"
            default=N
        else
            prompt="y/n"
            default=
        fi

        # Ask the question
        read -p "$1 [$prompt] " REPLY

        # Default?
        if [ -z "$REPLY" ]; then
            REPLY=$default
        fi

        # Check if the reply is valid
        case "$REPLY" in
            Y*|y*) return 0 ;;
            N*|n*) return 1 ;;
        esac
    done
}

function install_xserver-xorg-input-evdev {
## Debian releases after early 2017 break touch input - this will fix it
    set +e
    info PI-TFT "Checking for xserver-xorg-input-evdev:"
    PKG_STATUS=$(dpkg-query -W --showformat='${Status}\n' xserver-xorg-input-evdev|grep "install ok installed")
    if [ "" == "$PKG_STATUS" ]; then
        info PI-TFT "**** Installing xserver-xorg-input-evdev package ****"
        info PI-TFT "No xserver-xorg-input-evdev. Installing it now."
        apt update
        apt install -y xserver-xorg-input-evdev
    fi
    if [ ! -f /usr/share/X11/xorg.conf.d/45-evdev.conf ]; then
            info PI-TFT "Creating /usr/share/X11/xorg.conf.d/45-evdev.conf"
            ln -s /usr/share/X11/xorg.conf.d/10-evdev.conf /usr/share/X11/xorg.conf.d/45-evdev.conf
    fi
    info PI-TFT "**** xserver-xorg-input-evdev package installed ****"
    set -e
}

# update /boot/config.txt with appropriate values
function update_configtxt() {

    if grep -q "pi-tft" "/boot/config.txt"; then
        echo "Already have a tft-setup section in /boot/config.txt."
        echo "Adding new section, but please run:"
        echo "sudo nano /boot/config.txt"
        echo "...and remove any duplicate sections."
    fi

    if [ "${pitfttype}" == "22" ]; then
        # formerly: options fbtft_device name=adafruit22a gpios=dc:25 rotate=270 frequency=32000000
        overlay="dtoverlay=pitft22,rotate=270,speed=32000000,fps=20"
    fi

    if [ "${pitfttype}" == "28r" ]; then
        overlay="dtoverlay=pitft28-resistive,rotate=90,speed=62000000,fps=60"
    fi

    if [ "${pitfttype}" == "28c" ]; then
        overlay="dtoverlay=pitft28c,rotate=90,speed=62000000,fps=60"
    fi

    if [ "${pitfttype}" == "35r" ]; then
      ## overlay="dtoverlay=pitft35r,rotate=90,speed=32000000,fps=20"
      ## overlay="dtoverlay=pitft35r,rotate=90,speed=42000000,fps=20"
      ## overlay="dtoverlay=pitft35-resistive,rotate=270,speed=42000000,fps=30"
      overlay="dtoverlay=pitft35-resistive,rotate=270,speed=25000000,fps=20"
    fi
    
    if [ "${pitfttype}" == "35ro" ]; then
      ## overlay="dtoverlay=pitft35r,rotate=90,speed=32000000,fps=20"
      ## overlay="dtoverlay=pitft35r,rotate=90,speed=42000000,fps=20"
      overlay="dtoverlay=pitft35-resistive,rotate=270,speed=42000000,fps=30"
    fi

    if [ "${pitfttype}" == "elec22" ]; then
        overlay="dtoverlay=elec22"
    fi
    if [ "${pitfttype}" == "hy28b" ]; then
        overlay="dtoverlay=hy28b,rotate=90"
    fi
    if [ "${pitfttype}" == "jb35" ]; then
        overlay="dtoverlay=jbtek"
    fi
    if [ "${pitfttype}" == "kum35" ]; then
        overlay="dtoverlay=waveshare35a"
    fi
    if [ "${pitfttype}" == "sain32" ]; then
        overlay="dtoverlay=sainsmart32"
    fi
    if [ "${pitfttype}" == "sain35" ]; then
        overlay="dtoverlay=waveshare35a"
    fi
    if [ "${pitfttype}" == "wave32" ]; then
        overlay="dtoverlay=waveshare32b:rotate=270"
    fi
    if [ "${pitfttype}" == "wave35" ]; then
        overlay="dtoverlay=waveshare35a"
    fi
    if [ "${pitfttype}" == "wave35b" ]; then
        overlay="dtoverlay=waveshare35b"
    fi
    if [ "${pitfttype}" == "wave35h" ]; then
        overlay="hdmi_group=2
hdmi_mode=1
hdmi_mode=87
hdmi_cvt 480 320 60 6 0 0 0
dtoverlay=ads7846,cs=1,penirq=25,penirq_pull=2,speed=50000,keep_vref_on=0,swapxy=0,pmax=255,xohms=150,xmin=200,xmax=3900,ymin=200,ymax=3900
hdmi_drive=1"
    fi
    if [ "${pitfttype}" == "wave35o" ]; then
        overlay="dtoverlay=waveshare35a,speed=32000000,fps=50"
    fi
    if [ "${pitfttype}" == "wave40" ]; then
        overlay="dtoverlay=waveshare35a:rotate=270"
    fi
    if [ "${pitfttype}" == "wave50" ]; then
        overlay="hdmi_group=2
hdmi_mode=1
hdmi_mode=87
hdmi_cvt 800 480 60 6 0 0 0
dtoverlay=ads7846,cs=1,penirq=25,penirq_pull=2,speed=50000,keep_vref_on=0,swapxy=0,pmax=255,xohms=150,xmin=200,xmax=3900,ymin=200,ymax=3900
hdmi_drive=1"
    fi

    date=`date`
    if [ "${pitfttype}" == "pi70" ]; then
        cat >> /boot/config.txt <<EOF

# --- added by re4son-pi-tft-setup $date ---
# Flip screen so powerplug is at the top
lcd_rotate=2
# --- end re4son-pi-tft-setup $date ---
EOF

    else
    cat >> /boot/config.txt <<EOF

# --- added by re4son-pi-tft-setup $date ---
dtparam=spi=on
dtparam=i2c1=on
dtparam=i2c_arm=on
$overlay
###########################################
####  Overclocking the micro sdcard    ####
#### Uncomment  84 for Raspberry Pi 2  ####
# dtparam=sd_overclock=84
#### Uncomment 100 for Raspberry Pi 3  ####
# dtparam=sd_overclock=100
###########################################
# --- end re4son-pi-tft-setup $date ---
EOF
    fi
}

# currently for '90' rotation only
function update_xorg() {
    mkdir -p /etc/X11/xorg.conf.d

    cat > /etc/X11/xorg.conf.d/99-fbdev.conf <<EOF
Section "Device"
  Identifier "myfb"
  Driver "fbdev"
  Option "fbdev" "$FRAMEBUFFER"
EndSection
EOF

    if [ "${pitfttype}" == "28r" ]; then
        cat > /etc/X11/xorg.conf.d/99-calibration.conf <<EOF
Section "InputClass"
        Identifier      "calibration"
        MatchProduct    "stmpe-ts"
        Option  "Calibration"   "3800 200 200 3800"
        Option  "SwapAxes"      "1"
EndSection
EOF
    fi

    if [[ "${pitfttype}" =~ 35r.* ]]; then
        cat > /etc/X11/xorg.conf.d/99-calibration.conf <<EOF
Section "InputClass"
        Identifier      "calibration"
        MatchProduct    "stmpe-ts"
        Option  "Calibration"   "3800 120 200 3900"
        Option  "SwapAxes"      "1"
EndSection
EOF
    fi

    if [ "${pitfttype}" == "28c" ]; then
        cat > /etc/X11/xorg.conf.d/99-calibration.conf <<EOF
Section "InputClass"
         Identifier "captouch"
         MatchProduct "ft6x06_ts"
         Option "SwapAxes" "1"
         Option "InvertY" "1"
         Option "Calibration" "0 320 0 240"
EndSection
EOF
    fi
    if [ "${pitfttype}" == "hy28b" ]; then
        cat > /etc/X11/xorg.conf.d/99-calibration.conf <<EOF
Section "InputClass"
        Identifier      "calibration"
        MatchProduct    "ADS7843 Touchscreen"
        Option  "Calibration"   "3800 200 200 3800"
        Option  "SwapAxes"      "1"
EndSection
EOF
    fi
    if [ "${pitfttype}" == "wave32" ]; then
        cat > /etc/X11/xorg.conf.d/99-calibration.conf <<EOF
Section "InputClass"
         Identifier "calibration"
         MatchProduct "ADS7846 Touchscreen"
         Option "SwapAxes" "1"
         Option "Calibration" "160 3723 3896 181"
EndSection
EOF
    fi
    if [ "${pitfttype}" == "wave35" ] || [ "${pitfttype}" == "wave35b" ] || [ "${pitfttype}" == "wave35o" ] || [ "${pitfttype}" == "kum35" ] || [ "${pitfttype}" == "sain35" ]; then
        cat > /etc/X11/xorg.conf.d/99-calibration.conf <<EOF
Section "InputClass"
         Identifier "calibration"
         MatchProduct "ADS7846 Touchscreen"
         Option "SwapAxes" "1"
         Option "Calibration" "3933 227 241 3893"
EndSection
EOF
    fi
    if [ "${pitfttype}" == "wave35h" ]; then
        cat > /etc/X11/xorg.conf.d/99-calibration.conf <<EOF
Section "InputClass"
        Identifier      "calibration"
        MatchProduct    "ADS7846 Touchscreen"
        Option  "Calibration"   "190 3991 243 3895"
        Option  "SwapAxes"      "0"
EndSection
EOF
    fi
    if [ "${pitfttype}" == "wave40" ]; then
        cat > /etc/X11/xorg.conf.d/99-calibration.conf <<EOF
Section "InputClass"
        Identifier      "calibration"
        MatchProduct    "ADS7846 Touchscreen"
        Option  "Calibration"   "3950 172 3871 194"
        Option  "SwapAxes"      "1"
EndSection
EOF
    fi
    if [ "${pitfttype}" == "wave50" ]; then
        cat > /etc/X11/xorg.conf.d/99-calibration.conf <<EOF
Section "InputClass"
        Identifier      "calibration"
        MatchProduct    "ADS7846 Touchscreen"
        Option  "Calibration"   "138 3952 214 4002"
        Option  "SwapAxes"      "0"
EndSection
EOF
    fi

    libinput_path="/usr/share/X11/xorg.conf.d/60-libinput.conf"
    if [ -e $libinput_path ]; then
        info PI-TFT "Applying Neto calibration patch:"
        echo "Moving ${libinput_path} to ${target_homedir}/.60-libinput.conf.bak"
        mv "$libinput_path" ${target_homedir}/.60-libinput.conf.bak
    fi
}

function update_x11profile() {
    fbturbo_path="/usr/share/X11/xorg.conf.d/99-fbturbo.conf"
    if [ -e $fbturbo_path ]; then
        echo "Moving ${fbturbo_path} to ${target_homedir}"
        mv "$fbturbo_path" "$target_homedir"
    fi
##    if [ $HDMI ]; then
##	cat > "$fbturbo_path" <<EOF
##Section "Device"
##        Identifier      "Allwinner A10/A13 FBDEV"
##        Driver          "fbturbo"
##        Option          "fbdev" "/dev/fb0"

##        Option          "SwapbuffersWait" "true"
##EndSection
##EOF
##    fi
    if [ ! $HDMI ]; then
        if grep -q "export FRAMEBUFFER=/dev/fb1" "${target_homedir}/.profile"; then
            echo "Already had 'export FRAMEBUFFER=/dev/fb1'"
        elif grep -xq "export FRAMEBUFFER=/dev/fb0" "${target_homedir}/.profile"; then
            echo "Adding 'export FRAMEBUFFER=/dev/fb1'"
	    sed "${target_homedir}/.profile" -i -e "s/export FRAMEBUFFER=\/dev\/fb0/export FRAMEBUFFER=\/dev\/fb1/"
        else
            echo "Adding 'export FRAMEBUFFER=/dev/fb1'"
            date=`date`
            cat >> "${target_homedir}/.profile" <<EOF
# --- added by re4son-pi-tft-setup $date ---
export FRAMEBUFFER=/dev/fb1
# --- end re4son-pi-tft-setup $date ---
EOF
        fi
    else
        if grep -xq "export FRAMEBUFFER=/dev/fb0" "${target_homedir}/.profile"; then
            echo "Already had 'export FRAMEBUFFER=/dev/fb0'"
        elif grep -xq "export FRAMEBUFFER=/dev/fb0" "${target_homedir}/.profile"; then
            echo "Adding 'export FRAMEBUFFER=/dev/fb0'"
	    sed "${target_homedir}/.profile" -i -e "s/export FRAMEBUFFER=\/dev\/fb1/export FRAMEBUFFER=\/dev\/fb0/"
        else
            echo "Adding 'export FRAMEBUFFER=/dev/fb0'"
            date=`date`
            cat >> "${target_homedir}/.profile" <<EOF
# --- added by re4son-pi-tft-setup $date ---
export FRAMEBUFFER=/dev/fb0
# --- end re4son-pi-tft-setup $date ---
EOF
        fi
    fi
}

# currently for '90' rotation only
function update_pointercal() {
    if [ "${pitfttype}" == "28r" ] || [ "${pitfttype}" == "hy28b" ]; then
        cat > /etc/pointercal <<EOF
-30 -5902 22077792 4360 -105 -1038814 65536
EOF
    fi

    if [[ "${pitfttype}" =~ 35r.* ]]; then
        cat > /etc/pointercal <<EOF
8 -8432 32432138 5699 -112 -965922 65536
EOF
    fi

    if [ "${pitfttype}" == "wave35" ] || [ "${pitfttype}" == "wave35b" ] || [ "${pitfttype}" == "wave35o" ] || [ "${pitfttype}" == "kum35" ] || [ "${pitfttype}" == "sain35" ]; then
        cat > /etc/pointercal <<EOF
8 -8432 32432138 5699 -112 -965922 65536
EOF
    fi

    if [ "${pitfttype}" == "28c" ]; then
        cat > /etc/pointercal <<EOF
320 65536 0 -65536 0 15728640 65536
EOF
    fi

    if [ "${pitfttype}" == "4dpi" ]; then
        cat > /etc/pointercal <<EOF
5803 131 -2411836 53 4296 -937452 65536
EOF
    fi
    
    if [ "${pitfttype}" == "wave50" ]; then
        cat > /etc/pointercal <<EOF
13874 297 -2846048 -151 8401 -1722344 65536 800 480
EOF
    fi
    
    if [ "${pitfttype}" == "pi70" ]; then
        cat > /etc/pointercal <<EOF
66242 1508 -591604 531 67406 -647360 65536 800 480
EOF
    fi
}

function update_udev() {
    if [ "${pitfttype}" == "28r" ] || [[ "${pitfttype}" =~ 35r.* ]]; then
        cat > /etc/udev/rules.d/95-stmpe.rules <<EOF
SUBSYSTEM=="input", ATTRS{name}=="stmpe-ts", ENV{DEVNAME}=="*event*", SYMLINK+="input/touchscreen"
EOF
    fi

    if [ "${pitfttype}" == "28c" ]; then
        cat > /etc/udev/rules.d/95-ft6206.rules <<EOF
SUBSYSTEM=="input", ATTRS{name}=="ft6x06_ts", ENV{DEVNAME}=="*event*", SYMLINK+="input/touchscreen"
EOF
    fi
    if [ "${pitfttype}" == "hy28b" ]; then
        cat > /etc/udev/rules.d/95-stmpe.rules <<EOF
SUBSYSTEM=="input", ATTRS{name}=="ADS7843 Touchscreen", ENV{DEVNAME}=="*event*", SYMLINK+="input/touchscreen"
EOF
    fi

    if [ "${pitfttype}" == "wave32" ] || [ "${pitfttype}" == "wave35" ] || [ "${pitfttype}" == "wave35b" ] || [ "${pitfttype}" == "wave35o" ] || [ "${pitfttype}" == "kum35" ]   || [ "${pitfttype}" == "sain35" ] || [ "${pitfttype}" == "wave40" ] || [ "${pitfttype}" == "wave50" ]; then
        cat > /etc/udev/rules.d/95-ADS7846.rules <<EOF
SUBSYSTEM=="input", ATTRS{name}=="ADS7846 Touchscreen", ENV{DEVNAME}=="*event*", SYMLINK+="input/touchscreen"
EOF
    fi

if [ "${pitfttype}" == "4dpi" ]; then
        cat > /etc/udev/rules.d/95-AR1020.rules <<EOF
SUBSYSTEM=="input", ATTRS{name}=="AR1020 Touchscreen", ENV{DEVNAME}=="*event*", SYMLINK+="input/touchscreen"
EOF
    fi
    
if [ "${pitfttype}" == "pi70" ]; then
        cat > /etc/udev/rules.d/95-ft5406.rules <<EOF
SUBSYSTEM=="input", ATTRS{name}=="FT5406 memory based driver", ENV{DEVNAME}=="*event*", SYMLINK+="input/touchscreen"
EOF
    fi
}

function install_console() {
    if ! grep -q 'fbcon=map:10 fbcon=font:VGA8x8' /boot/cmdline.txt; then
        info PI-TFT "Updating /boot/cmdline.txt"
        sed -i 's/rootwait/rootwait fbcon=map:10 fbcon=font:VGA8x8/g' "/boot/cmdline.txt"
    else
        info PI-TFT "/boot/cmdline.txt already updated"
    fi
    if [ ! -f /etc/kbd/config ]; then
        info PI-TFT "Creating /etc/kbd/config"
        mkdir -p /etc/kbd
        touch /etc/kbd/config
    fi
    sed -i 's/BLANK_TIME=.*/BLANK_TIME=0/g' "/etc/kbd/config"
}

function uninstall_console() {
    sed -i 's/rootwait fbcon=map:10 fbcon=font:VGA8x8/rootwait/g' "/boot/cmdline.txt"
    sed -i 's/BLANK_TIME=0/BLANK_TIME=10/g' "/etc/kbd/config"
    info PI-TFT "Screen blanking time reset to 10 minutes"
}

function update_etcmodules() {
    if [ "${pitfttype}" == "28c" ]; then
        ts_module="ft6x06_ts"
    elif [ "${pitfttype}" == "28r" ] || [[ "${pitfttype}" =~ 35r.* ]]; then
        ts_module="stmpe_ts"
    elif [ "${pitfttype}" == "4dpi" ]; then
        ts_module="spi-bcm2835_dma
i2c-dev
pwmbl
ar1020-i2c
#4dpi_touch
4dpi"
        ## rotate screen
        sed -i 's/rootwait/4dpi.rotate=180 rootwait/g' "/boot/cmdline.txt"
    else
        return 0
    fi

    if grep -xq "$ts_module" "/etc/modules"; then
        info PI-TFT "Already had $ts_module"
    else
        info PI-TFT "Adding $ts_module"
        date=`date`
        cat >> /etc/modules <<EOF
# --- added by re4son-pi-tft-setup $date ---
$ts_module
# --- end re4son-pi-tft-setup $date ---
EOF
    fi
}

function install_onoffbutton() {
    echo "Adding rpi_power_switch to /etc/modules"
    if grep -xq "rpi_power_switch" "${chr}/etc/modules"; then
        echo "Already had rpi_power_switch"
    else
        echo "Adding rpi_power_switch"
        date=`date`
        cat >> /etc/modules <<EOF
# --- added by re4son-pi-tft-setup $date ---
rpi_power_switch
# --- end re4son-pi-tft-setup $date ---
EOF
    fi

    echo "Adding rpi_power_switch config to /etc/modprobe.d/re4son.conf"
    if grep -xq "options rpi_power_switch gpio_pin=27 mode=0" "${chr}/etc/modprobe.d/re4son.conf"; then
        info PI-TFT "Already had rpi_power_switch config"
    else
        info PI-TFT "Adding rpi_power_switch"
        date=`date`
        cat >> /etc/modprobe.d/re4son.conf <<EOF
# --- added by re4son-pi-tft-setup $date ---
options rpi_power_switch gpio_pin=27 mode=0
# --- end re4son-pi-tft-setup $date ---
EOF
    fi
}

function update_bootprefs() {
    # check init system (technique borrowed from raspi-config):
    info PI-TFT 'Checking init system...'
    if command -v systemctl > /dev/null && systemctl | grep -q '\-\.mount'; then
      echo "Found systemd"
      SYSTEMD=1
      set +e
      set -bm
      trap 'if [[ $? -eq 139 ]]; then info PI-TFT "Segfault can be ignored"; fi' CHLD
    elif [ -f /etc/init.d/cron ] && [ ! -h /etc/init.d/cron ]; then
      echo "Found sysvinit"
      SYSTEMD=0
    else
      bail "Unrecognised init system"
    fi

    if [ "${boot_pref}" == "cli" ]; then
      echo "Turning off boot-to-desktop"
      mv -f /etc/X11/xorg.conf.d/99-fbdev.conf ~ 2> /dev/null
      if [ -e /etc/init.d/lightdm ]; then
        if [ $SYSTEMD -eq 1 ]; then
          if [ -f /etc/systemd/system/getty.target.wants/getty@tty1.service ]; then
            rm -f /etc/systemd/system/getty.target.wants/getty@tty1.service
          fi
          systemctl set-default multi-user.target
          systemctl enable getty@tty1.service
          ## ln -fs /lib/systemd/system/getty@.service /etc/systemd/system/getty.target.wants/getty@tty1.service
        else
          update-rc.d lightdm disable 2
          sed /etc/inittab -i -e "s/1:2345:respawn:\/bin\/login -f pi tty1 <\/dev\/tty1 >\/dev\/tty1 2>&1/1:2345:respawn:\/sbin\/getty --noclear 38400 tty1/"
        fi
        info PI-TFT "Success"
      fi
    fi

    if [ "${boot_pref}" == "gui" ]; then
      echo "Turning on boot-to-desktop"
      mv -f ~/99-fbdev.conf /etc/X11/xorg.conf.d/ 2> /dev/null
      if [ -e /etc/init.d/lightdm ]; then
        if [ $SYSTEMD -eq 1 ]; then
          if [ -f /etc/systemd/system/getty.target.wants/getty@tty1.service ]; then
            rm -f /etc/systemd/system/getty.target.wants/getty@tty1.service
          fi
          systemctl set-default graphical.target
          systemctl enable getty@tty1.service
          ## ln -fs /lib/systemd/system/getty@.service /etc/systemd/system/getty.target.wants/getty@tty1.service
        else
          update-rc.d lightdm enable 2
          sed /etc/inittab -i -e "s/1:2345:respawn:\/bin\/login -f pi tty1 <\/dev\/tty1 >\/dev\/tty1 2>&1/1:2345:respawn:\/sbin\/getty --noclear 38400 tty1/"
        fi
        info PI-TFT "Success"
      fi
    fi
    echo
    read -p "Reboot to apply changes? (y/n): " -n 1 -r
    echo

    if [[ $REPLY =~ ^[Yy]$ ]]; then
       reboot
    fi
exit 0;
}

# MAIN

target_homedir="/home/pi"

args=$(getopt -uo 'hvuria:t:o:b:d:' -- $*)
[ $? != 0 ] && print_help
set -- $args

for i
do
    case "$i"
    in
        -h)
            print_help
            ;;
        -v)
            print_version
            ;;
        -a)
            user_name="$2"
            update_autologon
            echo
            read -p "Reboot to apply changes? (y/n): " -n 1 -r
            echo
            if [[ $REPLY =~ ^[Yy]$ ]]; then
                reboot
            fi
	    exit 0
            ;;
        -u)
            check_update
            ;;
        -r)
            removetft="YES"
            shift
            ;;
        -b)
            user_name="disable"
            update_autologon
            boot_pref="$2"
            update_bootprefs
            ;;
        -d)
            target_homedir="$2"
            info PI-TFT "Homedir = ${2}"
            shift
            shift
            ;;
        -t)
            pitfttype="$2"
            info PI-TFT "Type = ${2}"
            shift
            shift
            ;;
    esac
done

if [[ $EUID -ne 0 ]]; then
    bail "re4son-pi-tft-setup must be run as root. try: sudo re4son-pi-tft-setup"
fi

# check init system (technique borrowed from raspi-config):
info PI-TFT 'Checking init system...'
if command -v systemctl > /dev/null && systemctl | grep -q '\-\.mount'; then
  info PI-TFT "Found systemd"
  SYSTEMD=1
elif [ -f /etc/init.d/cron ] && [ ! -h /etc/init.d/cron ]; then
  info PI-TFT "Found sysvinit"
  SYSTEMD=0
else
  bail "Unrecognised init system"
fi

if grep -q boot /proc/mounts; then
    info PI-TFT "/boot is mounted"
else
    if ask "Cannot find /boot. Maybe it is not mounted. Shall I try mounting it?" "Y"; then
        info PI-TFT "Mounting /boot"
	mount /dev/mmcblk0p1 /boot
    fi
    if grep -q boot /proc/mounts; then
        info PI-TFT "/boot is mounted"
    else
        echo "/boot must be mounted. If you're sure it is, proceed - otherwise quit here and try: sudo mount /dev/mmcblk0p1 /boot"
	if ask "Continue?" "N"; then
	    info PI-TFT "Proceeding."
	else
	    bail "Aborting."
	fi
    fi
fi

if [[ ! -e "$target_homedir" || ! -d "$target_homedir" ]]; then
    bail "$target_homedir must be an existing directory (use -d /home/foo to specify)"
fi

if [ "${removetft}" == "YES" ]; then
    remove_tft || bail "Unable to remove tft configuration"
fi

if [ "${pitfttype}" != "4dpi" ] && \
   [ "${pitfttype}" != "28r" ] && \
   [ "${pitfttype}" != "28c" ] && \
   [ "${pitfttype}" != "35r" ] && \
   [ "${pitfttype}" != "35ro" ] && \
   [ "${pitfttype}" != "22" ] && \
   [ "${pitfttype}" != "elec22" ] && \
   [ "${pitfttype}" != "hy28b" ] && \
   [ "${pitfttype}" != "jb35" ] && \
   [ "${pitfttype}" != "kum35" ] && \
   [ "${pitfttype}" != "pi70" ] && \
   [ "${pitfttype}" != "sain32" ] && \
   [ "${pitfttype}" != "sain35" ] && \
   [ "${pitfttype}" != "wave32" ] && \
   [ "${pitfttype}" != "wave35" ] && \
   [ "${pitfttype}" != "wave35b" ] && \
   [ "${pitfttype}" != "wave35o" ] && \
   [ "${pitfttype}" != "wave35c" ] && \
   [ "${pitfttype}" != "wave35h" ] && \
   [ "${pitfttype}" != "wave40" ] && \
   [ "${pitfttype}" != "wave50" ]; then
    echo "Invalid screen. Choose a valid type from the list below."
    print_help
fi

## Start config

if [ "${pitfttype}" == "pi70" ] || [ "${pitfttype}" == "wave50" ] || [ "${pitfttype}" == "wave35h" ]; then
    HDMI="1"
fi

if [ $HDMI ]; then
    FRAMEBUFFER="/dev/fb0"
else
    FRAMEBUFFER="/dev/fb1"
fi

if [ "${pitfttype}" == "wave35c" ]; then
    pitfttype=kum35
fi

info PI-TFT "Updating X11 default calibration"
update_xorg || bail "Unable to update /etc/X11/xorg.conf.d/99-calibration.conf"

info PI-TFT "Updating X11 setup tweaks..."
update_x11profile || bail "Unable to update X11 setup"

info PI-TFT "Updating TSLib default calibration..."
update_pointercal || bail "Unable to update /etc/pointercal"

info PI-TFT "Updating SysFS rules for Touchscreen..."
update_udev || bail "Unable to update /etc/udev/rules.d"

# ask for console access
if ask "Would you like the console to appear on the PiTFT display?" "Y"; then
    info PI-TFT "Updating console to PiTFT..."
    install_console || bail "Unable to configure console"
else
    info PI-TFT "Making sure console doesn't use PiTFT"
    uninstall_console || bail "Unable to configure console"
fi

info PI-TFT "Updating /etc/modules..."
update_etcmodules || bail "Unable to update /etc/modules"

if [ "${pitfttype}" == "28r" ] || [ "${pitfttype}" == "28c" ] || [ "${pitfttype}" == "22" ]; then
    # ask for 'on/off' button
    if ask "Would you like GPIO #27 to act as a on/off button?" "Y"; then
        info PI-TFT "Adding GPIO #27 on/off to PiTFT..."
        install_onoffbutton || bail "Unable to add on/off button"
    fi
fi

if [ "${pitfttype}" == "elec22" ] || [ "${pitfttype}" == "jb35" ] || [ "${pitfttype}" == "sain32" ]; then
    echo "Your screen is configured for console use"
    echo "To output X on this screen, manual editing of some configuration files"
    echo "according to the manufacturers instructions might be required."
    echo
    echo "You can use the xinput-calibrator in the tools directory to calibrate the touch screen."
fi

info PI-TFT "Updating /boot/config.txt..."
update_configtxt || bail "Unable to update /boot/config.txt"

info PI-TFT "Installing dependencies..."
install_xserver-xorg-input-evdev

info PI-TFT "Success!"
echo
echo
read -p "Reboot to apply changes? (y/n): " -n 1 -r
echo

if [[ $REPLY =~ ^[Yy]$ ]]; then
  reboot
fi
