#!/bin/bash

# swp-install by Mason Nelson
# ===============================================================================
# Script to install SkywarnPlus. This script will determine the system type (ASL1/2, ASL3, or HamVoIP),
# install the required dependencies, download the latest version of SkywarnPlus from GitHub,
# configure the necessary permissions, and set up a crontab entry to run SkywarnPlus at a specified interval.
# This script also checks if the SkywarnPlus directory already exists and asks for user confirmation to remove it before continuing.
# Please note that this script should be run as root.

# This file is part of SkywarnPlus.
# SkywarnPlus is free software: you can redistribute it and/or modify it under the terms of
# the GNU General Public License as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version. SkywarnPlus is distributed in the hope
# that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with SkywarnPlus. If not, see <https://www.gnu.org/licenses/>.

clear

print_divider() {
    echo "========================================"
}

print_notice() {
    print_divider
    echo "This script is designed to automate the installation of SkywarnPlus."
    echo "Author: Mason Nelson"
    echo
    echo "NOTE: This script is an installer only and will NOT automate configuration."
    echo "Please edit the config.yaml file manually after installation."
    print_divider
    read -r -p "Would you like to continue? (Y/n): " CONTINUE
    CONTINUE=${CONTINUE:-y}
    if [[ "$CONTINUE" != [Yy] ]]; then
        print_divider
        echo "Installation aborted. Exiting."
        print_divider
        exit 1
    fi
}

check_root() {
    if [ "$EUID" -ne 0 ]; then
        print_divider
        echo "This script must be run as root. Exiting."
        print_divider
        exit 1
    fi
}

determine_system_type() {
    echo "Determining system type..."
    if [ -f /etc/debian_version ]; then
        . /etc/os-release
        OS=$ID
        VER=$VERSION_ID
        ASTERISK_VERSION=$(asterisk -V)
        if [[ "$ASTERISK_VERSION" =~ "Asterisk "([2-9][0-9]|[1-9][0-9]{2,}) ]]; then
            SYSTEM_TYPE="ASL3"
        else
            SYSTEM_TYPE="ASL1/2"
        fi
    elif [ -f /etc/arch-release ]; then
        OS=arch
        VER=$(uname -r)
        SYSTEM_TYPE="HamVoIP"
    else
        print_divider
        echo "Unsupported OS. This script supports only Debian and Arch."
        print_divider
        exit 1
    fi
}

confirm_system_type() {
    print_divider
    echo "Detected system type: $SYSTEM_TYPE."
    print_divider
    read -r -p "Is this correct? (Y/n): " CONFIRMATION
    CONFIRMATION=${CONFIRMATION:-y}
    if [[ "$CONFIRMATION" != [Yy] ]]; then
        print_divider
        echo "Please enter the correct system type:"
        echo "1 = ASL1/2"
        echo "3 = ASL3"
        echo "5 = HamVoIP"
        print_divider
        read -r -p "Enter the system type number: " SYSTEM_TYPE_INPUT
        SYSTEM_TYPE_INPUT=${SYSTEM_TYPE_INPUT:-3}
        case $SYSTEM_TYPE_INPUT in
            1) SYSTEM_TYPE="ASL1/2" ;;
            3) SYSTEM_TYPE="ASL3" ;;
            5) SYSTEM_TYPE="HamVoIP" ;;
            *)
                print_divider
                echo "Invalid input. Exiting."
                print_divider
                exit 1
            ;;
        esac
    fi
}

install_dependencies() {
    print_divider
    echo "Installing dependencies..."
    if [ "$OS" = "debian" ]; then
        apt update
        if [ "$SYSTEM_TYPE" = "ASL1/2" ]; then
            apt install -y unzip python3 python3-pip ffmpeg
            pip3 install ruamel.yaml requests python-dateutil pydub
        else
            apt install -y unzip python3 python3-pip ffmpeg python3-ruamel.yaml python3-requests python3-dateutil python3-pydub
        fi
    elif [ "$OS" = "arch" ]; then
        pacman -Syu --noconfirm
        pacman -S --noconfirm --needed ffmpeg
        if ! command -v pip &> /dev/null; then
            wget -q https://bootstrap.pypa.io/pip/3.5/get-pip.py
            python get-pip.py
        fi
        pip install requests python-dateutil pydub ruamel.yaml==0.15.100
    else
        print_divider
        echo "Unsupported OS version. Exiting."
        print_divider
        exit 1
    fi
}

check_existing() {
    if [ -d "/usr/local/bin/SkywarnPlus" ]; then
        print_divider
        echo "Existing SkywarnPlus installation detected. This installer script was intended for new installations."
        read -r -p "Would you like to run UpdateSWP.py instead?

[Y] Switch to UpdateSWP.py
[N] Continue with a fresh install after making a backup to SkywarnPlus_$(date +'%m-%d-%Y')/
    (you can grab your old config.yaml file from the backup)

Please choose an option (Y/n): " INSTALL_OPTION
        INSTALL_OPTION=${INSTALL_OPTION:-y}
        
        if [[ "$INSTALL_OPTION" =~ ^[Yy]$ ]]; then
            print_divider
            echo "Switching to UpdateSWP.py..."
            print_divider
            /usr/local/bin/SkywarnPlus/UpdateSWP.py
            exit 0
        else
            BACKUP_DIR="/usr/local/bin/SkywarnPlus_$(date +'%m-%d-%Y')"
            print_divider
            echo "Making a backup to $BACKUP_DIR..."
            if [ -d "$BACKUP_DIR" ]; then
                rm -rf "$BACKUP_DIR"
            fi
            mv /usr/local/bin/SkywarnPlus "$BACKUP_DIR"
            print_divider
            echo "Backup complete. Continuing with fresh installation..."
        fi
    fi
}

download_swp() {
    print_divider
    echo "Downloading SkywarnPlus..."
    wget -q -P /usr/local/bin https://github.com/Mason10198/SkywarnPlus/releases/latest/download/SkywarnPlus.zip
    unzip /usr/local/bin/SkywarnPlus.zip -d /usr/local/bin
    rm /usr/local/bin/SkywarnPlus.zip
}

configure_perms() {
    print_divider
    echo "Configuring permissions..."
    
    if [ "$SYSTEM_TYPE" = "ASL3" ]; then
        chown -R asterisk:asterisk /usr/local/bin/SkywarnPlus/
        chmod -R u+rw /usr/local/bin/SkywarnPlus/
    fi
    
    chmod +x /usr/local/bin/SkywarnPlus/*.py
}

remove_old_cron() {
    print_divider
    echo "Checking for \"old style\" crontab entry for SkywarnPlus.py..."
    CRONTAB_OLD=$(crontab -l | grep 'SkywarnPlus.py')
    if [ -n "$CRONTAB_OLD" ]; then
        echo "Found \"old style\" crontab entry for SkywarnPlus.py:"
        echo "$CRONTAB_OLD"
        echo "This must be removed to avoid conflicts. A new crontab entry will reside in /etc/cron.d/SkywarnPlus."
        echo "Removing \"old style\" crontab entry for SkywarnPlus.py..."
        (crontab -l | grep -v 'SkywarnPlus.py') | crontab -
        echo "\"Old style\" crontab entry for SkywarnPlus.py removed."
    else
        echo "No \"old style\" crontab entry found for SkywarnPlus.py."
    fi
    
    print_divider
    echo "Checking for existing crontab entry for ast_var_update.sh..."
    CRONTAB_AST=$(crontab -l | grep 'ast_var_update.sh')
    if [ -n "$CRONTAB_AST" ]; then
        echo "It looks like you have added a crontab entry for ast_var_update.sh - this functionality will now be handled by SkywarnPlus, and this crontab entry should be removed to avoid conflicts."
        read -r -p "Would you like to remove the crontab entry now? (Y/n): " choice
        choice=${choice:-y}
        if [[ "$choice" =~ ^[Yy]$ ]]; then
            echo "Removing old crontab entry for ast_var_update.sh..."
            (crontab -l | grep -v 'ast_var_update.sh') | crontab -
            echo "Old crontab entry for ast_var_update.sh removed."
        else
            echo "Crontab entry for ast_var_update.sh not removed."
        fi
    else
        echo "No existing crontab entry found for ast_var_update.sh."
    fi
}

setup_crontab() {
    print_divider
    CRON_FILE="/etc/cron.d/SkywarnPlus"
    
    if [ -f "$CRON_FILE" ]; then
        EXISTING_INTERVAL=$(grep -o '^\*/[0-9]*' "$CRON_FILE" | cut -d'/' -f2)
        if [ -n "$EXISTING_INTERVAL" ]; then
            echo "An existing crontab entry for SkywarnPlus was found with a $EXISTING_INTERVAL minute interval."
            echo
            echo "By default, the existing crontab entry will be kept."
            echo
            echo "To keep the existing $EXISTING_INTERVAL minute interval, press enter."
            echo "To change the interval, enter a different number of minutes."
            echo "To disable the crontab entry and require manual execution, enter '0'."
            read -r -p "Crontab interval ($EXISTING_INTERVAL): " CRONTAB_INTERVAL
            print_divider
            CRONTAB_INTERVAL=${CRONTAB_INTERVAL:-$EXISTING_INTERVAL}
        fi
    else
        echo "By default, a new crontab entry will be added to trigger SkywarnPlus (check for alerts) every 1 minute."
        echo
        echo "To keep the default 1 minute interval, press enter."
        echo "If you would like to increase this interval, enter a different number of minutes."
        echo "To disable the crontab entry and require manual execution, enter '0'."
        read -r -p "Crontab interval (1): " CRONTAB_INTERVAL
        CRONTAB_INTERVAL=${CRONTAB_INTERVAL:-1}
    fi

    if [ "$CRONTAB_INTERVAL" -eq 0 ]; then
        if [ -f "$CRON_FILE" ]; then
            rm "$CRON_FILE"
            echo "Existing crontab entry removed. You will need to run SkywarnPlus manually."
        else
            echo "No crontab entry created. You will need to run SkywarnPlus manually."
        fi
    else
        if [ "$SYSTEM_TYPE" = "ASL3" ]; then
            CRONTAB_ENTRY="*/$CRONTAB_INTERVAL * * * * asterisk /usr/local/bin/SkywarnPlus/SkywarnPlus.py"
        else
            CRONTAB_ENTRY="*/$CRONTAB_INTERVAL * * * * root /usr/local/bin/SkywarnPlus/SkywarnPlus.py"
        fi

        if grep -Fxq "$CRONTAB_ENTRY" "$CRON_FILE" 2>/dev/null; then
            echo "Crontab entry already exists. Skipping."
        else
            echo "$CRONTAB_ENTRY" > "$CRON_FILE" || {
                print_divider
                echo "Failed to create crontab entry. Exiting."
                print_divider
                exit 1
            }
        fi
    fi

    if [ "$SYSTEM_TYPE" = "ASL3" ]; then
        print_divider
        echo "This is an ASL3 system. In order for Supermon to display SkywarnPlus alerts on ASL3, a second crontab entry needs to be created to run ASL3_Supermon_Workaround.py as the root user."
        
        if [ -d "/var/www/html/supermon/" ]; then
            echo "It looks like you have Supermon installed, so it is recommended to create this crontab entry."
        else
            echo "It looks like you do not have Supermon installed, but you can still safely create this crontab entry in case you decide to use Supermon later."
        fi

        read -r -p "Would you like to create the crontab entry for ASL3_Supermon_Workaround.py now? (Y/n): " CREATE_SUPERMON_CRON
        CREATE_SUPERMON_CRON=${CREATE_SUPERMON_CRON:-y}

        if [[ "$CREATE_SUPERMON_CRON" =~ ^[Yy]$ ]]; then
            SUPERMON_CRON_FILE="/etc/cron.d/ASL3_Supermon_Workaround"
            SUPERMON_CRONTAB_ENTRY="* * * * * root /usr/local/bin/SkywarnPlus/ASL3_Supermon_Workaround.py"
            
            if grep -Fxq "$SUPERMON_CRONTAB_ENTRY" "$SUPERMON_CRON_FILE" 2>/dev/null; then
                echo "Supermon crontab entry already exists. Skipping."
            else
                echo "$SUPERMON_CRONTAB_ENTRY" > "$SUPERMON_CRON_FILE" || {
                    print_divider
                    echo "Failed to create Supermon crontab entry. Exiting."
                    print_divider
                    exit 1
                }
                echo "Supermon crontab entry created successfully."
            fi
        else
            echo "Supermon crontab entry not created."
        fi
    fi
}

edit_config() {
    print_divider
    echo "Installation and configuration complete. Please edit the config.yaml file as per your needs."
    print_divider
    read -r -p "Would you like to edit the config.yaml file now? (Y/n): " EDIT_CONFIG
    EDIT_CONFIG=${EDIT_CONFIG:-y}
    if [[ "$EDIT_CONFIG" =~ ^[Yy]$ ]]; then
        nano /usr/local/bin/SkywarnPlus/config.yaml
    else
        echo "You can edit the config.yaml file later using your preferred text editor."
    fi
}

main() {
    check_root
    print_notice
    determine_system_type
    confirm_system_type
    install_dependencies
    check_existing
    download_swp
    configure_perms
    remove_old_cron
    setup_crontab
    edit_config
}

main
