#!/usr/bin/bash

export PATH=/usr/sbin:$PATH
export DEBIAN_FRONTEND=noninteractive
set -euo pipefail
readonly COLOUR_RESET='\e[0m'
readonly aCOLOUR=(
    '\e[38;5;154m' # green  	| Lines, bullets and separators
    '\e[1m'        # Bold white	| Main descriptions
    '\e[90m'       # Grey		| Credits
    '\e[91m'       # Red		| Update notifications Alert
    '\e[33m'       # Yellow		| Emphasis
)
trap 'onCtrlC' INT
onCtrlC() {
    echo -e "${COLOUR_RESET}"
    exit 1
}

Show() {
    # OK
    if (($1 == 0)); then
        echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[0]}  OK  $COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
    # FAILED
    elif (($1 == 1)); then
        echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[3]}FAILED$COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
        exit 1
    # INFO
    elif (($1 == 2)); then
        echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[0]} INFO $COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
    # NOTICE
    elif (($1 == 3)); then
        echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[4]}NOTICE$COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
    fi
}

Warn() {
    echo -e "${aCOLOUR[3]}$1$COLOUR_RESET"
}

GreyStart() {
    echo -e "${aCOLOUR[2]}\c"
}

ColorReset() {
    echo -e "$COLOUR_RESET\c"
}


main() {
    DEPLOYMENT_DIR=$(pwd)/deployment
    BACKUP_DIR="$DEPLOYMENT_DIR/backup"
    DOWNLOAD_URL="$1"
    BACKUP_FILE="$BACKUP_DIR/$2"
    # Check if the deployment and backup directories exist, create them if not
    if [[ ! -d "$BACKUP_DIR" ]]; then
        echo "Backup directory does not exist. Creating: $BACKUP_DIR"
        mkdir -p "$BACKUP_DIR"
    fi

    # Check if the download URL is valid
    echo "Checking if the URL is valid: $DOWNLOAD_URL"
    if curl --head --silent --fail "$DOWNLOAD_URL" > /dev/null; then
        echo "URL is valid. Proceeding with download..."
    else
        Show 1 "Error: Invalid or inaccessible URL: $DOWNLOAD_URL"
        exit 1
    fi

    # Download the file and rename it to backup.zip
    wget -O "$BACKUP_FILE" "$DOWNLOAD_URL"

    # Check if the file was downloaded
    if [[ -f "$BACKUP_FILE" ]]; then
        Show 0 "Backup file successfully downloaded to: $BACKUP_FILE"
    else
        Show 1 "Error: Backup file was not downloaded."
        exit 1
    fi
}

main "$@"