#!/bin/bash

# Copyright © 2022 Musarubra US LLC, d.b.a. Skyhigh Security
# Shell script version of hybapp-switch-repo

DEFAULT_LOG_FILE='/var/log/hybapp-switch-repo.log'
DEFAULT_REPO_FILE='/etc/yum.repos.d/hybrid.repo'

# --- Initialization ---
TYPE="prod"
COMMAND="configure"
FORCE=false
INSECURE=false
DRYRUN=false
DEBUG=false
HYBVERSION=""

# --- Functions ---

log_message() {
    local level=$1
    local msg=$2
    local timestamp=$(date "+%b %d %H:%M:%S")
    echo "$timestamp $(basename "$0"): $msg" >> "$DEFAULT_LOG_FILE"
    if [ "$level" == "ERROR" ]; then
        echo "ERROR: $msg" >&2
    fi
}

usage() {
    echo "Usage: $(basename "$0") [options] <version>"
    echo "  -l, --list       show current configuration"
    echo "  -t, --testing    generate configuration for testing repository"
    echo "  -e, --export     generate configuration for Export repository"
    echo "  -s, --staging    generate configuration for staging repository"
    echo "  -p, --preprod    generate configuration for Pre Production repository"
    echo "  -P, --prod       generate configuration for Production repository"
    echo "  -n, --dry-run    show what configuration would be generated"
    echo "  -f, --force      force creation of repository configuration file"
    echo "  -i, --insecure   Use http instead of https"
    echo "  -d, --debug      debug mode"
    echo "  -h, --help       this help"
    exit 0
}

get_current_repo_config() {
    if [ -f "$DEFAULT_REPO_FILE" ]; then
        grep "^### Config: " "$DEFAULT_REPO_FILE" | head -n 1 | sed 's/^### Config: //'
    fi
}

# --- Parse Options ---
# Using a manual loop to handle long options 
while [[ $# -gt 0 ]]; do
    case "$1" in
        -l|--list)    COMMAND="list"; shift ;;
        -t|--testing) TYPE="testing"; shift ;;
        -e|--export)  TYPE="export"; shift ;;
        -s|--staging) TYPE="staging"; shift ;;
        -p|--preprod) TYPE="preprod"; shift ;;
        -P|--prod)    TYPE="prod"; shift ;;
        -n|--dry-run) DRYRUN=true; shift ;;
        -f|--force)   FORCE=true; shift ;;
        -i|--insecure) INSECURE=true; shift ;;
        -d|--debug)   DEBUG=true; shift ;;
        -h|--help)    usage ;;
        -*)           echo "Unknown option $1"; usage ;;
        *)            HYBVERSION="$1"; shift ;;
    esac
done

# --- Main Logic ---

if [ "$COMMAND" == "list" ]; then
    CONFIG=$(get_current_repo_config)
    if [ -n "$CONFIG" ]; then
        echo "Current Configuration: $CONFIG"
    else
        echo "Could not parse configuration file"
    fi
    exit 0
fi

# Validate version input 
if [ -z "$HYBVERSION" ]; then
    usage
fi

# Normalize version if it is numeric (e.g., 1 -> 1.0.0) 
if [[ "$HYBVERSION" =~ ^[0-9]+(\.[0-9]+(\.[0-9]+)?)?$ ]]; then
    dots=$(echo "$HYBVERSION" | tr -cd '.' | wc -c)
    while [ "$dots" -lt 2 ]; do
        HYBVERSION="${HYBVERSION}.0"
        ((dots++))
    done
fi

# Validate via Regex 
if [[ "$HYBVERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    # Standard version format
    :
elif [[ $HYBVERSION =~ ^[[:alnum:]_+-]+$ ]]; then
    echo "WARNING: Unrecognized version string. Repository configuration might be invalid." >&2 
else
    echo "ERROR: Invalid or missing repository configuration." >&2 
    exit 1
fi

# --- Generate Config (create_repo_config)  ---
PROTO="https"
[ "$INSECURE" = true ] && PROTO="http"

# Logic for host URLs 
case "$TYPE" in
    testing)
        if [ "$HYBVERSION" == "develop" ]; then
            HOSTURL="hybrid-repo.dev.webwasher.com/staging/$HYBVERSION/"
        else
            # Default fallback for testing not explicitly defined in source
            HOSTURL="hybrid-repo.dev.webwasher.com/staging/$HYBVERSION/"
        fi ;;
    export)  HOSTURL="hybrid-repo.dev.webwasher.com/export/$HYBVERSION/" ;;
    staging) HOSTURL="staging.hybrid-repo.dev.webwasher.com/hybapp/$HYBVERSION/" ;;
    preprod) HOSTURL="preprod.hybrid-repo.webwasher.com/hybapp/$HYBVERSION/" ;;
    prod)    HOSTURL="hybrid-repo.webwasher.com/hybapp/$HYBVERSION/" ;;
    *)       echo "Unknown repository type '$TYPE'"; exit 1 ;;
esac

# Create the config string 
CFG="### Config: Hybrid Appliance - ${HYBVERSION} (${TYPE})
# Autogenerated repository configuration.
# Do not edit. Changes will be overwritten.
# Use hybrid-switch-repo to reconfigure repository.

[hybapp-${HYBVERSION}-${TYPE}]
name = Hybrid Appliance ${HYBVERSION} (${TYPE}) Repository
baseurl=${PROTO}://${HOSTURL}base/
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-HYBAPP
       file:///etc/pki/rpm-gpg/RPM-GPG-KEY-SLOS1
gpgcheck=1
enabled=1
"

if [ "$DRYRUN" = true ]; then
    echo "$CFG" 
    exit 0
fi

# Write to temp file and test 
TMPDIR=$(mktemp -d)
TMPFILE="${TMPDIR}/hybrid.repo"
echo "$CFG" > "$TMPFILE"

if [ "$FORCE" = false ]; then
    echo "Testing connectivity to repository. This may take a while." 
    dnf -y -q --setopt=reposdir="$TMPDIR" makecache >/dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo "Repository $HYBVERSION not reachable. Repository re-configuration failed!" >&2 
        log_message "ERROR" "Repository $HYBVERSION not reachable."
        rm -rf "$TMPDIR"
        exit 1
    fi
fi

# Success: Copy to final destination 
cp "$TMPFILE" "$DEFAULT_REPO_FILE"
log_message "NOTICE" "Hybrid Appliance - ${HYBVERSION} (${TYPE})"
echo 'Repository configuration has been updated.'
echo 'Now run "dnf upgrade dnf && dnf upgrade" to perform the actual upgrade.'

rm -rf "$TMPDIR"
