#!/bin/bash

. /etc/profile
#. /etc/systemconfig

HOSTNAME=`/usr/bin/hostnamectl hostname`

function msg(){
    /usr/bin/lh_notify-send --app-name="LinHES" --icon=dialog-information "$1" "$2"
}

function check_installer_user(){
    if [[ "$(whoami)" = 'km' ]]; then
        echo "Running lh_system_start as installer user km. Exiting."
        exit 1
    fi
}

function applyUIsettings(){
    /usr/bin/lh_apply_UI_settings.sh
    msg "Welcome to LinHES 9!"
}

function x11vnc_setup(){
    konsole -e /bin/bash -i -c "echo 'Create VNC password.' && x11vnc --storepasswd"
    mkdir -p ~/.vnc
    touch ~/.vnc/x11vnc.log
    sudo /usr/bin/systemctl enable --now x11vnc.service
}

function bashrc_setup(){
    if ! grep -q 'alias rscp=' ~/.bashrc; then
        echo -e "\nalias rscp='rsync -a --info=progress2'" >> ~/.bashrc
    fi
    if ! grep -q 'alias rsmv=' ~/.bashrc; then
        echo -e "alias rsmv='rsync -a --info=progress2 --remove-source-files'" >> ~/.bashrc
    fi
}

function nanorc_setup(){
    sudo sed -i 's/# set tabsize.*/set tabsize 4/' /etc/nanorc
    sudo sed -i 's/# set tabstospaces.*/set tabstospaces/' /etc/nanorc
    sudo sed -i 's/.*\/usr\/share\/nano\/\*.nanorc.*/include \/usr\/share\/nano\/\*.nanorc/' /etc/nanorc
}

function storage_scan(){
    sudo add_storage.py --report > /dev/null
    if [ -e /tmp/scan_report ]; then
        msg "New Storage Found" "Run add_storage.py for details."
    fi
}

function install_lh_apps(){
    #install programs that are not needed on the iso
    #check network connection
    netwait=0
    while ! timeout 1 nc -zw1 1.1.1.1 443; do
       1 [ $netwait -gt 60 ] && msg "Cancelling Setup" "Could not connect to the internet to complete setup. Check the internet connection and from Konsole run lh_system_start.sh." && exit 1
        msg "Waiting for internet connectivity..." "Connect to the internet to complete setup."
        ((netwait++))
        sleep 5
    done
    msg "Installing apps."
    konsole -e /bin/bash -i -c "sudo pacman -Syyy --noconfirm archlinux-keyring && sudo pacman -Syyyu --noconfirm mythtv mythplugins-mytharchive mythplugins-mythmusic mythplugins-mythweb && flatpak install tv.plex.PlexHTPC --noninteractive --assumeyes && sudo flatpak override tv.plex.PlexHTPC --filesystem=/run/lirc/lircd"
    status=$?
    [ $status -eq 1 ] && msg "Cancelling Setup" "Could not connect to the internet to complete setup. Check the internet connection and from Konsole run lh_system_start.sh." && exit 1
    gen_lib_xml.py
}

function sql_setup(){
    sudo mkdir -p /data/srv/mysql
    sudo mariadb-install-db --user=mysql --basedir=/usr --datadir=/data/srv/mysql
    sudo systemctl enable --now mariadb.service
    mysql_tzinfo_to_sql /usr/share/zoneinfo | sudo mysql -u root mysql
    sudo mariadb -u root < /usr/share/linhes/templates/db/permissions.sql
    mythtv-setup -O theme=LinHES
    sed -e "s/apheleia/${HOSTNAME}/g" /usr/share/linhes/templates/db/custom.sql > /tmp/custom.sql.fixed
    sudo mariadb -u root mythconverg < /tmp/custom.sql.fixed
}

function localweb_setup(){
    konsole -e /bin/bash -i -c "sudo pacman -Syyy --noconfirm linhes-web"
    sudo cp /etc/lighttpd/lighttpd.conf /etc/lighttpd/lighttpd.conf.orig
    sudo cp /usr/share/linhes/templates/lighttpd.conf.template /etc/lighttpd/lighttpd.conf
    sudo systemctl enable --now lighttpd.service
}

function first_configure(){
    if [ ! -f ~/.config/lh_configured ]; then
        msg "New install of LinHES. Starting setup."
        if [ -f /etc/systemconfig ]; then
            SystemType=$(grep SystemType= /etc/systemconfig | cut -d '"' -f 2)
        else
            SystemType=$(kdialog --title "LinHES System Type" --combobox "Select the LinHES System Type:                               " "MasterBackend" "FrontendOnly" "DesktopOnly" --default "MasterBackend")
            echo "SystemType=\"$SystemType\"" | sudo tee /etc/systemconfig
        fi
        install_lh_apps
        nanorc_setup
        bashrc_setup
        x11vnc_setup
        #apply settings for specific system types
        msg "Setup as $SystemType"
        if [ $SystemType = "MasterBackend" ]; then
            # create media directory structure
            sudo mkdir -p /data/storage/disk0
            sudo create_media_dirs.sh /data/storage/disk0
            sudo ln -s /data/storage/disk0/media/ /myth
            # setup DB
            sql_setup
            # run mythtv-setup
            # need to run twice for default db install/upgrade
            mythtv-setup
            sudo systemctl enable --now mythbackend.service
            # run mythfilldatabase
            #nice -n 19 mythfilldatabase --quiet &
            #msg "Guide data is being loaded." "Until this completes some shows will appear as unknown in the program guide."
            localweb_setup
        elif [ $SystemType = "FrontendOnly" ]; then
            msg "Frontend Only"
            #Frontend_only cmds
            # create media directory structure
            sudo mkdir -p /data/storage/disk0
            sudo create_media_dirs.sh /data/storage/disk0
        elif [ $SystemType = "DesktopOnly" ]; then
            msg "Desktop Only"
            #Frontend_only cmds
            # create media directory structure
            sudo mkdir -p /data/storage/disk0
            sudo create_media_dirs.sh /data/storage/disk0
            touch ~/.config/lh_dontrunmythfrontend
        fi
        touch ~/.config/lh_configured
    fi
}

function start_user_apps() {
    if [ -f ~/.config/lh_startuserapps ]; then
        msg "Starting User Apps..."
        source ~/.config/lh_startuserapps
    fi
}

function start_myth() {
    STARTCMD="/usr/bin/mythfrontend --disable-autodiscovery --noupnp --quiet --syslog local6"
    if [ ! -f ~/.config/lh_dontrunmythfrontend ]; then
        msg "Starting MythFrontend..."
        $STARTCMD 2>&1 &
    fi
}

#-------MAIN-------
check_installer_user
#apply settings for all system types
applyUIsettings
first_configure
/usr/bin/enableIRWake.sh &
storage_scan
start_user_apps
start_myth
