#!/bin/bash -e

function usage {
    cat <<EOF
Invalid option: $1

Valid options:
    -m, --metrics     Configure Metrics System for Dev.
    -a, --apps        Configure Flatpak for Staging.
    -o, --ostree      Configure OSTree for Staging (checked daily).
    -j, --journal     Configure systemd journal to be persistent.
EOF
}

METRICS=true
APPS=true
OSTREE=true
JOURNAL=false
if [ $# -gt 0 ]; then
    METRICS=false
    APPS=false
    OSTREE=false
    while [ $# -gt 0 ]; do
        case "$1" in
            -m|--metrics)
                METRICS=true
                shift
                ;;
            -a|--apps)
                APPS=true
                shift
                ;;
            -o|--ostree)
                OSTREE=true
                shift
                ;;
            -j|--journal)
                JOURNAL=true
                shift
                ;;
            *)
                usage $1
                exit 1
                ;;
        esac
    done
fi

# Check that script was run with superuser privileges.
if [[ $EUID != 0 ]]; then
    echo "$0 requires superuser privileges."
    exit 1
fi

# Check if master image.
if ostree admin status | grep -q "master"; then
    read -p "Detected master image. Are you sure you wish to continue? [Y/n] " response
    case $response in
        [yY]* | '') ;;
        *) exit 1 ;;
    esac
fi

# Configure persistent systemd journal
if $JOURNAL; then
    echo "Configuring systemd journal to be persistent."
    mkdir /var/log/journal
    systemd-tmpfiles --create --prefix /var/log/journal
fi

# Enable systemd coredumps storage
eos-enable-coredumps /etc

# Set metrics env to dev.
if $METRICS; then
    echo "Configuring Metrics System for Dev."
    eos-select-metrics-env dev
fi

# Change OSTree and Flatpak servers to staging.
if $OSTREE || $APPS; then
    # Change the Flatpak runtime and apps server URLs to the dev stage.
    if $APPS; then
        # Get the HTTP password for the dev repos.
        read -p "OSTree password: " OSTREE_PASSWORD
        if [ -z "$OSTREE_PASSWORD" ]; then
            echo "error: No password supplied" >&2
            exit 1
        fi

        eos-stage-flatpak dev "${OSTREE_PASSWORD}"
    fi

    # Change OSTree server URL to the dev stage.
    if $OSTREE; then
        eos-stage-ostree dev
    fi
fi

echo "All done!"
