pre_install() {
    :
#!/bin/bash
#
# Copyright (c) 2009 - 2023 ExpressVPN. All rights reserved.
#

# The list of our required dependencies - filled in by package.sh
DEB_PACKAGE_DEPENDENCIES=('libc6 >= 2.28' )

# Check that the user's system has the required dependencies
# if not, then fail the install (exit-ing with a non-zero exit status achieves this)
function verify_dependencies() {
    # If we're not on debian, then early exit
    # RPM correctly checks dependencies before attempting
    # to install a package, but debian does not
    if [[ ! -f /etc/debian_version ]]; then
        return 0
    fi

    for orig_dep in "${DEB_PACKAGE_DEPENDENCIES[@]}"; do
        local dep
        # Simplify processing by first removing white space
        dep=$(echo "$orig_dep" | tr -d ' ')
        if [[ "$dep" =~ ">=" ]]; then
            local package=${dep%%>=*}
            local required_version=${dep##*>=}
            local installed_version
            installed_version=$(dpkg-query -W -f'${Version}' "$package")

            # shellcheck disable=SC2181
            if [[ $? -ne 0 ]]; then
                echo "The required package $package is not installed, please install it before proceeding"
                exit 1
            fi

            if ! dpkg --compare-versions "$installed_version" ">=" "$required_version"; then
                echo "Installed $package version does not meet minimum requirements: ${required_version} but found ${installed_version}. Aborting."
                exit 1
            fi
        fi
    done
}

# Ensure the user's system has our required dependencies or abort installation
verify_dependencies

# Restore resolv.conf file
if grep -q "Generated by expressvpn" /etc/resolv.conf 2>/dev/null; then
	# reset chattr
	if [ -x /usr/bin/chattr ] ; then
		/usr/bin/chattr -i /etc/resolv.conf || true
	fi

	# restore previous resolv.conf
	bakfile=/var/lib/expressvpn/resolv.conf.orig
	if [ -L "$bakfile" ]; then
		mv "$bakfile" /etc/resolv.conf
	elif [ -f "$bakfile" ]; then
		cat "$bakfile" > /etc/resolv.conf
		rm /var/lib/expressvpn/resolv.conf.orig
	fi
fi

# Versions up to and including 3.8.0 shipped some files in
# /usr/lib/expressvpn and manually installed them into /etc or other
# locations. These files are now shipped directly the target
# location. We need to deal with the previous target file file, which
# the admin may have edited. We don't try to preserve the edits but we
# avoid simply deleting them so they can be recovered.
#
# Note that the target is not necessarily the same place as the file
# now lives in the package,
# e.g. /etc/systemd/system/expressvpn.service actually became
# {/usr}/lib/systemd/system/expressvpn.service.
function upgrade_3_8_0_file_move() {
    local source=$1
    local target=$2
    # If the old file doesn't exist we can relax.
    if ! [ -f "${target}" ] ; then
	return
    fi

    # This pre-install script runs before the new package is unpacked,
    # i.e. with the previous version (if any) still installed. If the
    # previous source filename no longer exists then we are upgrading
    # from something newer than 3.8.0 and the admin has recreated the
    # old target file for some reason. Leave it as is.
    if ! [ -f "${source}" ] ; then
	return
    fi

    # If the target is a symlink then there's no data loss in removing
    # it.
    if [ -L "${target}" ] ; then
	rm -f "${target}" || true
	return
    fi

    # Since we are upgrading from 3.8.0 or older the source file in
    # the old package should still be present during this pre-install
    # script. If the copy in /etc is identical then we can safely
    # remove it.
    if cmp -s "${target}" "${source}" ; then
	rm -f "${target}" || true
	return
    fi

    # The file has been modified (or the old file is, unexpectedly,
    # absent) so make a backup.
    mv -f "${target}" "${target}".bak || true
}

upgrade_3_8_0_file_move /usr/lib/expressvpn/expressvpn.service /etc/systemd/system/expressvpn.service || true
upgrade_3_8_0_file_move /usr/lib/expressvpn/expressvpn.init /etc/init.d/expressvpn || true
upgrade_3_8_0_file_move /usr/lib/expressvpn/bash-completion /usr/share/bash-completion/completions/expressvpn || true
upgrade_3_8_0_file_move /usr/lib/expressvpn/bash-completion /etc/bash_completion.d/expressvpn || true

}
post_install() {
    :
#!/bin/bash
#
# Copyright (c) 2009 - 2023 ExpressVPN. All rights reserved.
#

SCRIPT_DIR=/usr/lib/expressvpn
WORK_DIR=/var/lib/expressvpn
USER=${SUDO_USER:-"$USER"}
LOGFILE=${XVPN_INSTALLER_LOGFILE:-"/dev/null"}

function install_init() {
    /etc/init.d/expressvpn restart
}

function install_update_rcd() {
    /usr/sbin/update-rc.d expressvpn defaults || true
}

function install_systemd() {
    systemctl enable expressvpn
    systemctl restart expressvpn
}

function generate_certs() {
    mkdir -p "$WORK_DIR/certs"
    chown root "$WORK_DIR/certs"
    chmod 755 "$WORK_DIR/certs"
    /usr/sbin/expressvpnd --workdir "$WORK_DIR" generate-client-ca
    /usr/sbin/expressvpnd --workdir "$WORK_DIR" generate-client-certs
    rm -f "$WORK_DIR/certs/client.req"
    rm -f "$WORK_DIR/certs/clientca.srl"
    chmod 644 "$WORK_DIR/certs/client.key"
}

function install_chrome_helper() {
    echo "Installing Chrome extension helper..."
    if [ -f "${SCRIPT_DIR}/chrome/com.expressvpn.helper.json" ]; then
        sudo -u "${USER}" bash -c 'mkdir -p "${HOME}/.config/google-chrome/NativeMessagingHosts"'
        sudo -u "${USER}" bash -c 'cp "/usr/lib/expressvpn/chrome/com.expressvpn.helper.json" "${HOME}/.config/google-chrome/NativeMessagingHosts/com.expressvpn.helper.json"'
        sudo -u "${USER}" bash -c 'mkdir -p "${HOME}/.config/chromium/NativeMessagingHosts"'
        sudo -u "${USER}" bash -c 'cp "/usr/lib/expressvpn/chrome/com.expressvpn.helper.json" "${HOME}/.config/chromium/NativeMessagingHosts/com.expressvpn.helper.json"'
        sudo -u "${USER}" bash -c 'mkdir -p "${HOME}/.config/BraveSoftware/Brave-Browser/NativeMessagingHosts"'
        sudo -u "${USER}" bash -c 'cp "/usr/lib/expressvpn/chrome/com.expressvpn.helper.json" "${HOME}/.config/BraveSoftware/Brave-Browser/NativeMessagingHosts/com.expressvpn.helper.json"'
    fi
}

function install_firefox_helper() {
    echo "Installing Firefox extension helper..."
    if [ -f "${SCRIPT_DIR}/firefox/com.expressvpn.helper.json" ]; then
        sudo -u "${USER}" bash -c 'mkdir -p "${HOME}/.mozilla/native-messaging-hosts"'
        sudo -u "${USER}" bash -c 'cp "/usr/lib/expressvpn/firefox/com.expressvpn.helper.json" "${HOME}/.mozilla/native-messaging-hosts/com.expressvpn.helper.json"'
    fi
}

function install_service() {
    echo "Installing expressvpn service..."
    # If systemctl exists we assume systemd, otherwise we try a few distro specific variations
    if command -v systemctl &>/dev/null; then
        install_systemd
    elif [ -f "/etc/debian_version" ]; then
        # Debian/Ubuntu logic, not systemd so assuming sysv
        install_init
        install_update_rcd
    else # Nothing we recognised.
        BOLD='\e[1m'
        REG='\e[0m'
        echo -e "${BOLD}Unable to detect a supported Linux distribution.${REG}"
        echo -e "Service will not be started automatically."
        echo -e ""
        echo -e "You will need to arrange to run the following as a service:"
        echo -e ""
        echo -e "  ${BOLD}/usr/sbin/expressvpnd --client-version 3.82.0 --client-build 2${REG}"
        echo -e ""
    fi
}

function upgrade_userdata() {
    # Upgrade userdata to v2
    if [ -e "$WORK_DIR/userdata.dat" ] && [ ! -e "$WORK_DIR/userdata2.dat" ]; then
        mv "$WORK_DIR/userdata.dat" "$WORK_DIR/userdata2.dat"
    fi

    # Upgrade userdata to shared library
    if [ -e "$WORK_DIR/userdata2.dat" ] && [ ! -e "$WORK_DIR/data/e21fb121.bin" ]; then
        echo "Upgrade in progress..."

        mkdir -p "$WORK_DIR/data"
        chmod 700 "$WORK_DIR/data"
        /usr/sbin/expressvpnd \
            --workdir "$WORK_DIR" \
            --client-version "3.82.0" \
            --client-build "2" \
            migrate >> "${LOGFILE}" 2>&1
    fi
}

function kill_agent() {
    # kill any running expressvpn-agent process from a previous installation
    /usr/bin/expressvpn-agent --kill-existing
}

function prompt_enablelogs() {
    # Show nothing if logging is already enabled.
    if grep -q XVPN_VERBOSE /etc/default/expressvpn || grep -q XVPN_DEBUG /etc/default/expressvpn ; then
        return
    fi

    BOLD='\e[1m'
    REG='\e[0m'
    echo
    echo -e "${BOLD}Help improve ExpressVPN${REG}:"
    echo -e ""
    echo -e "Enable the collection of diagnostic information to report bugs and give"
    echo -e "feedback on this beta version of ExpressVPN. To enable run:"
    echo -e ""
    echo -e "  ${BOLD}sudo /usr/lib/expressvpn/expressvpn-enable-beta-diagnostics${REG}"
    echo -e ""
}

generate_certs >> "${LOGFILE}" 2>&1 || true
upgrade_userdata || true
install_chrome_helper >> "${LOGFILE}" 2>&1 || true
install_firefox_helper >> "${LOGFILE}" 2>&1 || true
install_service >> "${LOGFILE}" 2>&1
kill_agent >> "${LOGFILE}" 2>&1

if false ; then
    prompt_enablelogs
fi

# always success
exit 0

}
pre_upgrade() {
    :
#!/bin/bash
#
# Copyright (c) 2009 - 2023 ExpressVPN. All rights reserved.
#

# The list of our required dependencies - filled in by package.sh
DEB_PACKAGE_DEPENDENCIES=('libc6 >= 2.28' )

# Check that the user's system has the required dependencies
# if not, then fail the install (exit-ing with a non-zero exit status achieves this)
function verify_dependencies() {
    # If we're not on debian, then early exit
    # RPM correctly checks dependencies before attempting
    # to install a package, but debian does not
    if [[ ! -f /etc/debian_version ]]; then
        return 0
    fi

    for orig_dep in "${DEB_PACKAGE_DEPENDENCIES[@]}"; do
        local dep
        # Simplify processing by first removing white space
        dep=$(echo "$orig_dep" | tr -d ' ')
        if [[ "$dep" =~ ">=" ]]; then
            local package=${dep%%>=*}
            local required_version=${dep##*>=}
            local installed_version
            installed_version=$(dpkg-query -W -f'${Version}' "$package")

            # shellcheck disable=SC2181
            if [[ $? -ne 0 ]]; then
                echo "The required package $package is not installed, please install it before proceeding"
                exit 1
            fi

            if ! dpkg --compare-versions "$installed_version" ">=" "$required_version"; then
                echo "Installed $package version does not meet minimum requirements: ${required_version} but found ${installed_version}. Aborting."
                exit 1
            fi
        fi
    done
}

# Ensure the user's system has our required dependencies or abort installation
verify_dependencies

# Restore resolv.conf file
if grep -q "Generated by expressvpn" /etc/resolv.conf 2>/dev/null; then
	# reset chattr
	if [ -x /usr/bin/chattr ] ; then
		/usr/bin/chattr -i /etc/resolv.conf || true
	fi

	# restore previous resolv.conf
	bakfile=/var/lib/expressvpn/resolv.conf.orig
	if [ -L "$bakfile" ]; then
		mv "$bakfile" /etc/resolv.conf
	elif [ -f "$bakfile" ]; then
		cat "$bakfile" > /etc/resolv.conf
		rm /var/lib/expressvpn/resolv.conf.orig
	fi
fi

# Versions up to and including 3.8.0 shipped some files in
# /usr/lib/expressvpn and manually installed them into /etc or other
# locations. These files are now shipped directly the target
# location. We need to deal with the previous target file file, which
# the admin may have edited. We don't try to preserve the edits but we
# avoid simply deleting them so they can be recovered.
#
# Note that the target is not necessarily the same place as the file
# now lives in the package,
# e.g. /etc/systemd/system/expressvpn.service actually became
# {/usr}/lib/systemd/system/expressvpn.service.
function upgrade_3_8_0_file_move() {
    local source=$1
    local target=$2
    # If the old file doesn't exist we can relax.
    if ! [ -f "${target}" ] ; then
	return
    fi

    # This pre-install script runs before the new package is unpacked,
    # i.e. with the previous version (if any) still installed. If the
    # previous source filename no longer exists then we are upgrading
    # from something newer than 3.8.0 and the admin has recreated the
    # old target file for some reason. Leave it as is.
    if ! [ -f "${source}" ] ; then
	return
    fi

    # If the target is a symlink then there's no data loss in removing
    # it.
    if [ -L "${target}" ] ; then
	rm -f "${target}" || true
	return
    fi

    # Since we are upgrading from 3.8.0 or older the source file in
    # the old package should still be present during this pre-install
    # script. If the copy in /etc is identical then we can safely
    # remove it.
    if cmp -s "${target}" "${source}" ; then
	rm -f "${target}" || true
	return
    fi

    # The file has been modified (or the old file is, unexpectedly,
    # absent) so make a backup.
    mv -f "${target}" "${target}".bak || true
}

upgrade_3_8_0_file_move /usr/lib/expressvpn/expressvpn.service /etc/systemd/system/expressvpn.service || true
upgrade_3_8_0_file_move /usr/lib/expressvpn/expressvpn.init /etc/init.d/expressvpn || true
upgrade_3_8_0_file_move /usr/lib/expressvpn/bash-completion /usr/share/bash-completion/completions/expressvpn || true
upgrade_3_8_0_file_move /usr/lib/expressvpn/bash-completion /etc/bash_completion.d/expressvpn || true

}
post_upgrade() {
    :
#!/bin/bash
#
# Copyright (c) 2009 - 2023 ExpressVPN. All rights reserved.
#

SCRIPT_DIR=/usr/lib/expressvpn
WORK_DIR=/var/lib/expressvpn
USER=${SUDO_USER:-"$USER"}
LOGFILE=${XVPN_INSTALLER_LOGFILE:-"/dev/null"}

function install_init() {
    /etc/init.d/expressvpn restart
}

function install_update_rcd() {
    /usr/sbin/update-rc.d expressvpn defaults || true
}

function install_systemd() {
    systemctl enable expressvpn
    systemctl restart expressvpn
}

function generate_certs() {
    mkdir -p "$WORK_DIR/certs"
    chown root "$WORK_DIR/certs"
    chmod 755 "$WORK_DIR/certs"
    /usr/sbin/expressvpnd --workdir "$WORK_DIR" generate-client-ca
    /usr/sbin/expressvpnd --workdir "$WORK_DIR" generate-client-certs
    rm -f "$WORK_DIR/certs/client.req"
    rm -f "$WORK_DIR/certs/clientca.srl"
    chmod 644 "$WORK_DIR/certs/client.key"
}

function install_chrome_helper() {
    echo "Installing Chrome extension helper..."
    if [ -f "${SCRIPT_DIR}/chrome/com.expressvpn.helper.json" ]; then
        sudo -u "${USER}" bash -c 'mkdir -p "${HOME}/.config/google-chrome/NativeMessagingHosts"'
        sudo -u "${USER}" bash -c 'cp "/usr/lib/expressvpn/chrome/com.expressvpn.helper.json" "${HOME}/.config/google-chrome/NativeMessagingHosts/com.expressvpn.helper.json"'
        sudo -u "${USER}" bash -c 'mkdir -p "${HOME}/.config/chromium/NativeMessagingHosts"'
        sudo -u "${USER}" bash -c 'cp "/usr/lib/expressvpn/chrome/com.expressvpn.helper.json" "${HOME}/.config/chromium/NativeMessagingHosts/com.expressvpn.helper.json"'
        sudo -u "${USER}" bash -c 'mkdir -p "${HOME}/.config/BraveSoftware/Brave-Browser/NativeMessagingHosts"'
        sudo -u "${USER}" bash -c 'cp "/usr/lib/expressvpn/chrome/com.expressvpn.helper.json" "${HOME}/.config/BraveSoftware/Brave-Browser/NativeMessagingHosts/com.expressvpn.helper.json"'
    fi
}

function install_firefox_helper() {
    echo "Installing Firefox extension helper..."
    if [ -f "${SCRIPT_DIR}/firefox/com.expressvpn.helper.json" ]; then
        sudo -u "${USER}" bash -c 'mkdir -p "${HOME}/.mozilla/native-messaging-hosts"'
        sudo -u "${USER}" bash -c 'cp "/usr/lib/expressvpn/firefox/com.expressvpn.helper.json" "${HOME}/.mozilla/native-messaging-hosts/com.expressvpn.helper.json"'
    fi
}

function install_service() {
    echo "Installing expressvpn service..."
    # If systemctl exists we assume systemd, otherwise we try a few distro specific variations
    if command -v systemctl &>/dev/null; then
        install_systemd
    elif [ -f "/etc/debian_version" ]; then
        # Debian/Ubuntu logic, not systemd so assuming sysv
        install_init
        install_update_rcd
    else # Nothing we recognised.
        BOLD='\e[1m'
        REG='\e[0m'
        echo -e "${BOLD}Unable to detect a supported Linux distribution.${REG}"
        echo -e "Service will not be started automatically."
        echo -e ""
        echo -e "You will need to arrange to run the following as a service:"
        echo -e ""
        echo -e "  ${BOLD}/usr/sbin/expressvpnd --client-version 3.82.0 --client-build 2${REG}"
        echo -e ""
    fi
}

function upgrade_userdata() {
    # Upgrade userdata to v2
    if [ -e "$WORK_DIR/userdata.dat" ] && [ ! -e "$WORK_DIR/userdata2.dat" ]; then
        mv "$WORK_DIR/userdata.dat" "$WORK_DIR/userdata2.dat"
    fi

    # Upgrade userdata to shared library
    if [ -e "$WORK_DIR/userdata2.dat" ] && [ ! -e "$WORK_DIR/data/e21fb121.bin" ]; then
        echo "Upgrade in progress..."

        mkdir -p "$WORK_DIR/data"
        chmod 700 "$WORK_DIR/data"
        /usr/sbin/expressvpnd \
            --workdir "$WORK_DIR" \
            --client-version "3.82.0" \
            --client-build "2" \
            migrate >> "${LOGFILE}" 2>&1
    fi
}

function kill_agent() {
    # kill any running expressvpn-agent process from a previous installation
    /usr/bin/expressvpn-agent --kill-existing
}

function prompt_enablelogs() {
    # Show nothing if logging is already enabled.
    if grep -q XVPN_VERBOSE /etc/default/expressvpn || grep -q XVPN_DEBUG /etc/default/expressvpn ; then
        return
    fi

    BOLD='\e[1m'
    REG='\e[0m'
    echo
    echo -e "${BOLD}Help improve ExpressVPN${REG}:"
    echo -e ""
    echo -e "Enable the collection of diagnostic information to report bugs and give"
    echo -e "feedback on this beta version of ExpressVPN. To enable run:"
    echo -e ""
    echo -e "  ${BOLD}sudo /usr/lib/expressvpn/expressvpn-enable-beta-diagnostics${REG}"
    echo -e ""
}

generate_certs >> "${LOGFILE}" 2>&1 || true
upgrade_userdata || true
install_chrome_helper >> "${LOGFILE}" 2>&1 || true
install_firefox_helper >> "${LOGFILE}" 2>&1 || true
install_service >> "${LOGFILE}" 2>&1
kill_agent >> "${LOGFILE}" 2>&1

if false ; then
    prompt_enablelogs
fi

# always success
exit 0

}
pre_remove() {
    :
#!/bin/bash
#
# Copyright (c) 2009 - 2023 ExpressVPN. All rights reserved.
#
USER=${SUDO_USER:-"$USER"}

# Disconnect before remove. OK to fail.
if sudo -u "${USER}" /usr/bin/expressvpn status | grep -q Connected 2>/dev/null ; then
	sudo -u "${USER}" /usr/bin/expressvpn disconnect

	sleep 2
fi

# Stop engine daemon
if command -v systemctl > /dev/null 2>&1; then
	systemctl stop expressvpn
else
	if [ -x /etc/init.d/expressvpn ]; then
		/etc/init.d/expressvpn stop
	fi
fi


}
post_remove() {
    :
#!/bin/bash
#
# Copyright (c) 2009 - 2023 ExpressVPN. All rights reserved.
#

# Only do full uninstall when purge
if [ "$1" = "purge" ]; then
	rm -rf /var/lib/expressvpn || true
	rm -rf /var/log/expressvpn || true
	rm -rf /var/run/expressvpn || true
fi

}
