#!/bin/bash -e

# FreeBSD (DEF-60779). FreeBSD has no bash in its base system, so this part is POSIX sh, and it comes first: run as
# "sh install-patchman.sh", sh executes it and exits before it would parse the bash-only Linux installer below.
# On Linux the uname check is all of it that runs. Same options and the same flow as on Linux, with pkg(8): the
# signed Patchman repository, the patchman-client package, the registration key, the outbound IP, then enable
# and start the service. Real-time scanning is Linux-only.
# PATCHMAN_DOWNLOAD_URL (default https://download.patchman.co) overrides where the repository and key are read from.
freebsd_install ()
{
    set -e

    download_url="${PATCHMAN_DOWNLOAD_URL:-https://download.patchman.co}"
    fbsd_custom=0
    fbsd_ip=""
    fbsd_realtime=""

    fbsd_is_ipv4 ()
    {
        echo "$1" | awk -F. 'NF == 4 && $0 ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ && $1 <= 255 && $2 <= 255 && $3 <= 255 && $4 <= 255 { ok = 1 } END { exit !ok }'
    }

    fbsd_is_private ()
    {
        echo "$1" | awk -F. '$1 == 10 || ($1 == 172 && $2 >= 16 && $2 <= 31) || ($1 == 192 && $2 == 168) { p = 1 } END { exit !p }'
    }

    while [ $# -gt 0 ]; do
        case "$1" in
            -a)
                fbsd_ip="$2"
                fbsd_is_ipv4 "$fbsd_ip" || { echo "Invalid IPv4 address specified: $fbsd_ip"; exit 1; }
                shift
                ;;
            --ip-address=*)
                fbsd_ip="${1#*=}"
                fbsd_is_ipv4 "$fbsd_ip" || { echo "Invalid IPv4 address specified: $fbsd_ip"; exit 1; }
                ;;
            -c)
                fbsd_custom=1
                ;;
            --realtime=yes|--realtime=no)
                fbsd_realtime="${1#*=}"
                ;;
            --realtime=*)
                echo "Invalid real-time setting specified: ${1#*=}"
                exit 1
                ;;
            *)
                if fbsd_is_ipv4 "$1"; then
                    fbsd_ip="$1"
                else
                    echo "Invalid argument specified: $1"
                    exit 1
                fi
                ;;
        esac
        shift
    done

    if [ "$(id -u)" != 0 ]; then
        echo "Please run the installer as root."
        exit 1
    fi

    # Packages are built for FreeBSD 14 and 15 on amd64 only.
    fbsd_major="$(freebsd-version -u | sed 's/\..*//')"
    fbsd_arch="$(uname -m)"
    if [ "$fbsd_major" != 14 ] && [ "$fbsd_major" != 15 ]; then
        echo "Unsupported FreeBSD version, terminating installation ($(freebsd-version -u)); FreeBSD 14 and 15 are supported"
        exit 1
    fi
    if [ "$fbsd_arch" != amd64 ]; then
        echo "Unsupported architecture, terminating installation ($fbsd_arch); only amd64 is supported on FreeBSD"
        exit 1
    fi

    # pkg(8) itself is not installed until it is bootstrapped.
    if ! pkg -N >/dev/null 2>&1; then
        env ASSUME_ALWAYS_YES=yes pkg bootstrap
    fi
    fbsd_abi="$(pkg config abi)"

    # Installed with a registration key: nothing to do. Installed without one (an earlier run stopped at the key
    # prompt): skip the repository and package steps but finish the configuration, so "run the installer again" works.
    fbsd_install=1
    fbsd_configure=1
    if pkg info -e patchman-client; then
        fbsd_install=0
        if [ -s /etc/patchman/license/key ]; then
            echo "Patchman is already installed."
            echo ""
            fbsd_configure=0
        else
            echo "Patchman is installed but has no registration key yet; continuing with its configuration."
            echo ""
        fi
    fi

    if [ $fbsd_configure -eq 1 ]; then
        if [ $fbsd_install -eq 1 ] && [ $fbsd_custom -eq 0 ] && [ ! -f /usr/local/cpanel/cpanel ] &&
                [ ! -f /usr/local/directadmin/directadmin ] && [ ! -d /usr/local/psa/ ]; then
            echo "Patchman was not able to detect standard platform software to integrate with, and"
            echo "will not be able to determine which directories it needs to scan. This means that"
            echo "the software will not be able to perform its functions."
            echo ""
            echo "If you are using a custom integration method, you can continue the installation"
            echo "and configure Patchman for the custom integration afterwards. If you are not using"
            echo "a custom integration method, please contact customer support at support@patchman.co"
            echo "for more information."
            echo ""
            printf "Continue? [y/N] "
            read fbsd_continue || true

            if [ "$fbsd_continue" != "y" ] && [ "$fbsd_continue" != "Y" ]; then
                exit 1
            fi

            echo ""
            echo "Note: If you want to avoid this question during future installations, you can supply"
            echo "      the -c option to this script, e.g.:"
            echo ""
            echo "      sh $0 -c"
            echo ""

            sleep 2
        fi

        if [ -z "$fbsd_ip" ]; then
            # The address this server reaches the internet from: the one on the interface of its route to the
            # same host the Linux installer asks the routing table about.
            fbsd_if="$(route -n get 139.162.216.201 2>/dev/null | awk '$1 == "interface:" { print $2 }')"
            fbsd_source="$(ifconfig "$fbsd_if" inet 2>/dev/null | awk '$1 == "inet" { print $2; exit }')"

            if fbsd_is_private "$fbsd_source"; then
                echo "Patchman can't automatically detect the outbound IP on this machine, since you're"
                echo "using a NAT. Please manually provide the outbound IPv4 address that we should use."
                echo ""
                printf "IP address: "
                read fbsd_ip || true

                if ! fbsd_is_ipv4 "$fbsd_ip"; then
                    echo "Invalid IPv4 address specified, aborting."
                    exit 1
                fi

                echo ""
                echo "Note: If you want to avoid this question during future installations, you can supply"
                echo "      the address to the script using the -a or --ip-address options, e.g.:"
                echo ""
                echo "      sh $0 -a $fbsd_ip"
                echo "      sh $0 --ip-address=$fbsd_ip"
                echo ""

                sleep 2
            fi
        fi

        if [ $fbsd_install -eq 1 ]; then
            # The Patchman repository, signed with the key fetched next. ${ABI} is left for pkg to expand, so the
            # repository follows the system through a FreeBSD upgrade.
            mkdir -p /usr/local/etc/pkg/repos /usr/local/etc/pkg/keys
            fetch -q -o /usr/local/etc/pkg/keys/patchman.pub "$download_url/repo/freebsd/patchman.pub"
            cat > /usr/local/etc/pkg/repos/patchman.conf <<FBSD_REPO
patchman: {
  url: "$download_url/repo/freebsd/\${ABI}",
  signature_type: "pubkey",
  pubkey: "/usr/local/etc/pkg/keys/patchman.pub",
  enabled: yes
}
FBSD_REPO

            echo "Using the Patchman repository for $fbsd_abi"
            # Not "-r patchman": that limits dependency lookups to our repository too, and the agent's one
            # dependency, GNU patch (devel/patch, run as gpatch), comes from the FreeBSD repository.
            # patchman-client exists only in ours.
            pkg update
            pkg install -y patchman-client
        fi

        if [ ! -s /etc/patchman/license/key ]; then
            printf "Please enter your registration key: "
            fbsd_reg_key=
            read fbsd_reg_key || true

            # Closed stdin (EOF) or an empty answer: stop rather than write an empty key and start an agent that
            # cannot register. The package stays installed; run the installer again with the key.
            if [ -z "$fbsd_reg_key" ]; then
                echo ""
                echo "No registration key entered; the agent was not configured or started." >&2
                echo "Run the installer again, or write the key to /etc/patchman/license/key and run:" >&2
                echo "  sysrc patchman_enable=YES && service patchman start" >&2
                exit 1
            fi

            echo "$fbsd_reg_key" > /etc/patchman/license/key
        else
            echo "Registration key found"
        fi

        if [ -n "$fbsd_ip" ]; then
            if [ -f /etc/patchman/patchman.ini ] && grep -q "^ip=" /etc/patchman/patchman.ini; then
                sed -i '' "s/^ip=.*$/ip=$fbsd_ip/" /etc/patchman/patchman.ini
            else
                printf "\n[network]\nip=%s\n" "$fbsd_ip" >> /etc/patchman/patchman.ini
            fi
        fi

        # Running the installer asks for the agent to run: enable it at boot and start it, as on Linux.
        sysrc patchman_enable=YES >/dev/null
        fbsd_status=0
        service patchman start || fbsd_status=$?

        if [ $fbsd_status -eq 0 ]; then
            service patchman status >/dev/null 2>&1 || fbsd_status=$?
        fi

        echo ""
        printf "=%.s" $(seq 1 "$(tput cols 2>/dev/null || echo 80)")
        printf "\n\n"

        if [ $fbsd_status -eq 0 ]; then
            echo "Installation finished. Patchman is now installed and running!"
            echo ""
            echo "Remember to approve the new server in your Patchman Portal account to start scanning."
            echo ""
        else
            echo "An error occurred. Please contact support@patchman.co and mail the files in /var/log/patchman/ for troubleshooting purposes."
            echo ""
            exit 0
        fi
    fi

    # The real-time scanning component (patchman-client-realtime) exists for Linux only.
    if [ "$fbsd_realtime" = yes ]; then
        echo "Real-time scanning is not available on FreeBSD; it was not installed."
    fi

    echo ""
    exit 0
}

if [ "$(uname -s)" = FreeBSD ]; then
    freebsd_install "$@"
fi

inet_aton ()
{
    IFS="." read -a ipaddr <<< "$1"

    for i in 3 2 1 0
    do
        (( ip32 += ipaddr[3-i] * (256 ** i) ))
    done

    echo $ip32
}

range_match ()
{
    ip=`inet_aton "$1"`
    range_min=`inet_aton "$2"`
    range_max=`inet_aton "$3"`

    if [ $ip -gt $(($range_min - 1)) ] && [ $ip -lt $(($range_max + 1)) ]; then
        echo 1;
    else
        echo 0;
    fi
}

is_ipv4_address ()
{
    if [ `echo $1 | grep -Pc "^([0-2]?\d)?\d.([0-2]?\d)?\d.([0-2]?\d)?\d.([0-2]?\d)?\d$"` -eq 0 ]; then
        echo 0;
        return;
    fi

    IFS="." read -a ipaddr <<< "$1"

    for i in 3 2 1 0
    do
        if [ ${ipaddr[3-i]} -lt 0 ] || [ ${ipaddr[3-i]} -gt 255 ]; then
            echo 0;
            return;
        fi
    done

    echo 1;
}

is_package_installed ()
{
    if [ -e /etc/redhat-release ]; then
        rpm -q "$1" >> /dev/null 
        return $?
    elif [ -e /etc/debian_version ]; then
        return `dpkg --get-selections "$1" | grep -v "deinstall" | grep -c "$1" >> /dev/null`
    else
        echo "Unsupported OS version, terminating installation"
        exit 1
    fi
}

custom_integration=0
ip_address=""
install_client=1
install_realtime=-1 # -1 means unspecified or unanswered, this is to avoid asking to install real-time when a --realtime flag is passed

while [ $# -gt 0 ]
do
    arg="$1"

    case $arg in
        -a)
        ip_address="$2"
        if [ `is_ipv4_address "$ip_address"` -eq 0 ]; then
            echo "Invalid IPv4 address specified: $ip_address"
            exit 1
        fi
        shift
        ;;
        --ip-address=*)
        ip_address="${arg#*=}"
        if [ `is_ipv4_address "$ip_address"` -eq 0 ]; then
            echo "Invalid IPv4 address specified: $ip_address"
            exit 1
        fi
        ;;
        -c)
        custom_integration=1
        ;;
        --realtime=*)
        if [ "${arg#*=}" == "yes" ]; then
            install_realtime=1
        elif [ "${arg#*=}" == "no" ]; then
            install_realtime=0
        else
            echo "Invalid real-time setting specified: ${arg#*=}"
            exit 1
        fi
        ;;
        *)
        if [ `is_ipv4_address "$1"` -eq 1 ]; then
            ip_address="$1"
        else
            echo "Invalid argument specified: $1"
            exit 1
        fi
        ;;
    esac
    shift
done

if is_package_installed patchman-client; then
    echo "Patchman is already installed."
    echo ""
    install_client=0
fi

if [ $install_client -eq 1 ] ; then
    if [ $custom_integration -eq 0 ]; then
        if [ ! -f /usr/local/cpanel/cpanel ] &&
                [ ! -f /usr/local/directadmin/directadmin ] &&
                [ ! -d /usr/local/psa/ ]; then
            echo "Patchman was not able to detect standard platform software to integrate with, and"
            echo "will not be able to determine which directories it needs to scan. This means that"
            echo "the software will not be able to perform its functions."
            echo ""
            echo "If you are using a custom integration method, you can continue the installation"
            echo "and configure Patchman for the custom integration afterwards. If you are not using"
            echo "a custom integration method, please contact customer support at support@patchman.co"
            echo "for more information."
            echo ""
            echo -n "Continue? [y/N] "
            read -n 1 continue

            if [ "$continue" != "" ]; then
                echo ""
            fi

            if [ "$continue" != "y" ] && [ "$continue" != "Y" ]; then
                exit 1
            fi

            echo ""
            echo "Note: If you want to avoid this question during future installations, you can supply"
            echo "      the -c option to this script, e.g.:"
            echo ""
            echo "      /bin/bash -e $0 -c"
            echo ""

            sleep 2
        fi
    fi

    if [ `is_ipv4_address "$ip_address"` -eq 0 ]; then
        source_address=`ip r get 139.162.216.201 | grep -Po "(?<=src ).+"`

        if [ `range_match $source_address 10.0.0.0 10.255.255.255` -eq 1 ] ||
                [ `range_match $source_address 172.16.0.0 172.31.255.255` -eq 1 ] ||
                [ `range_match $source_address 192.168.0.0 192.168.255.255` -eq 1 ]; then
            echo "Patchman can't automatically detect the outbound IP on this machine, since you're"
            echo "using a NAT. Please manually provide the outbound IPv4 address that we should use."
            echo ""
            echo -n "IP address: "
            read ip_address

            if [ `is_ipv4_address "$ip_address"` -eq 0 ]; then
                echo "Invalid IPv4 address specified, aborting."
                exit 1
            fi

            echo ""
            echo "Note: If you want to avoid this question during future installations, you can supply"
            echo "      the address to the script using the -a or --ip-address options, e.g.:"
            echo ""
            echo "      /bin/bash -e $0 -a $ip_address"
            echo "      /bin/bash -e $0 --ip-address=$ip_address"
            echo ""

            sleep 2
        fi
    fi

    if [ -e /etc/redhat-release ]; then
        version="`sed -n 's/.* release \([0-9][0-9]*\).*/\1/p' /etc/redhat-release`"

        if [ "$version" = "6" ] || [ "$version" = "7" ] || [ "$version" = "8" ] || [ "$version" = "9" ]; then
            wget https://download.patchman.co/repo/rhel/RPM-GPG-KEY-Patchman -O /etc/pki/rpm-gpg/RPM-GPG-KEY-Patchman
        else
            echo "Unsupported RHEL version, terminating installation (`cat /etc/redhat-release`)"
            exit 1
        fi

        wget https://download.patchman.co/repo/rhel/patchman.repo -O /etc/yum.repos.d/patchman.repo

        yum -y install patchman-client
    elif [ -e /etc/debian_version ]; then
        apt-get -y install apt-transport-https

        which lsb_release >/dev/null || apt-get -y install lsb-release

        version="`lsb_release -c -s`"

        if [ "$version" = "wheezy" ] || [ "$version" = "quantal" ] || [ "$version" = "raring" ] || [ "$version" = "saucy" ] || [ "$version" = "trusty" ]; then
            wget https://download.patchman.co/repo/debian/patchman.list -O /etc/apt/sources.list.d/patchman.list
            wget https://download.patchman.co/repo/debian/patchman.gpg -O- | apt-key add -

            sed -i "s/ \w\+ main$/ wheezy main/" /etc/apt/sources.list.d/patchman.list
        elif [ "$version" = "jessie" ] || [ "$version" = "utopic" ] || [ "$version" = "vivid" ] || [ "$version" = "wily" ] || [ "$version" = "xenial" ] || [ "$version" = "yakkety" ]; then
            wget https://download.patchman.co/repo/debian/patchman.list -O /etc/apt/sources.list.d/patchman.list
            wget https://download.patchman.co/repo/debian/patchman.gpg -O- | apt-key add -

            sed -i "s/ \w\+ main$/ jessie main/" /etc/apt/sources.list.d/patchman.list
        elif [ "$version" = "stretch" ] || [ "$version" = "zesty" ] || [ "$version" = "artful" ] || [ "$version" = "bionic" ]; then
            wget https://download.patchman.co/repo/debian/patchman.list -O /etc/apt/sources.list.d/patchman.list
            wget https://download.patchman.co/repo/debian/patchman.gpg -O /usr/share/keyrings/patchman-archive-keyring.gpg

            sed -i "s/ / [signed-by=\/usr\/share\/keyrings\/patchman-archive-keyring.gpg] /" /etc/apt/sources.list.d/patchman.list
            sed -i "s/ \w\+ main$/ stretch main/" /etc/apt/sources.list.d/patchman.list
        elif [ "$version" = "buster" ] || [ "$version" = "cosmic" ] || [ "$version" = "disco" ] || [ "$version" = "eoan" ] || [ "$version" = "focal" ]; then
            wget https://download.patchman.co/repo/debian/patchman.list -O /etc/apt/sources.list.d/patchman.list
            wget https://download.patchman.co/repo/debian/patchman.gpg -O /usr/share/keyrings/patchman-archive-keyring.gpg

            sed -i "s/ / [signed-by=\/usr\/share\/keyrings\/patchman-archive-keyring.gpg] /" /etc/apt/sources.list.d/patchman.list
            sed -i "s/ \w\+ main$/ buster main/" /etc/apt/sources.list.d/patchman.list
        elif [ "$version" = "bullseye" ] || [ "$version" = "groovy" ] || [ "$version" = "hirsute" ] || [ "$version" = "impish" ]; then
            wget https://download.patchman.co/repo/debian/patchman.list -O /etc/apt/sources.list.d/patchman.list
            wget https://download.patchman.co/repo/debian/patchman.gpg -O /usr/share/keyrings/patchman-archive-keyring.gpg

            sed -i "s/ / [signed-by=\/usr\/share\/keyrings\/patchman-archive-keyring.gpg] /" /etc/apt/sources.list.d/patchman.list
            sed -i "s/ \w\+ main$/ bullseye main/" /etc/apt/sources.list.d/patchman.list
        elif [ "$version" = "bookworm" ] || [ "$version" = "jammy" ] || [ "$version" = "kinetic" ] || [ "$version" = "lunar" ] || [ "$version" = "mantic" ] || [ "$version" = "noble" ] || [ "$version" = "oracular" ] || [ "$version" = "plucky" ]; then
            wget https://download.patchman.co/repo/debian/patchman.list -O /etc/apt/sources.list.d/patchman.list
            wget https://download.patchman.co/repo/debian/patchman.gpg -O /usr/share/keyrings/patchman-archive-keyring.gpg

            sed -i "s/ / [signed-by=\/usr\/share\/keyrings\/patchman-archive-keyring.gpg] /" /etc/apt/sources.list.d/patchman.list
            sed -i "s/ \w\+ main$/ bookworm main/" /etc/apt/sources.list.d/patchman.list
        elif [ "$version" = "trixie" ] || [ "$version" = "questing" ] || [ "$version" = "resolute" ]; then
            wget https://download.patchman.co/repo/debian/patchman.list -O /etc/apt/sources.list.d/patchman.list
            wget https://download.patchman.co/repo/debian/patchman.gpg -O /usr/share/keyrings/patchman-archive-keyring.gpg

            sed -i "s/ / [signed-by=\/usr\/share\/keyrings\/patchman-archive-keyring.gpg] /" /etc/apt/sources.list.d/patchman.list
            sed -i "s/ \w\+ main$/ trixie main/" /etc/apt/sources.list.d/patchman.list
        else
            echo "Unsupported Debian version, terminating installation (`lsb_release -d -s`)"
            exit 1
        fi

        apt-get update

        apt-get -y install patchman-client
    else
        echo "Unsupported OS version, terminating installation"
        exit 1
    fi

    if [ ! -e /etc/patchman/license/key ]; then
        echo -n "Please enter your registration key: "
        read reg_key

        echo "$reg_key" > /etc/patchman/license/key
    else
        echo "Registration key found"
    fi

    if [ `is_ipv4_address $ip_address` -eq 1 ]; then
        if [ -f /etc/patchman/patchman.ini ] && [ `grep -c "^ip=" /etc/patchman/patchman.ini` -gt 0 ]; then
            sed -i "s/^ip=.\+$/ip=$ip_address/" /etc/patchman/patchman.ini
        else
            echo -e "\n[network]\nip=$ip_address" >> /etc/patchman/patchman.ini
        fi
    fi

    exec 3>&1
    exec 4>&2

    status=`(service patchman start >&3 2>&4 && echo 0) || echo $?`

    if [ $status -eq 0 ]; then
        status=`(service patchman status >/dev/null 2>&1 && echo 0) || echo $?`
    fi

    echo ""
    printf "=%.s" $(seq 1 `tput cols`)
    echo -e "\n"

    if [ $status -eq 0 ]; then
        echo "Installation finished. Patchman is now installed and running!"
        echo ""
        echo "Remember to approve the new server in your Patchman Portal account to start scanning."
        echo ""
    else
        echo "An error occurred. Please contact support@patchman.co and mail the files in /var/log/patchman/ for troubleshooting purposes."
        echo ""
        exit 0
    fi
fi

if is_package_installed patchman-client-realtime; then
    # real-time is already installed, no need to do anything
    exit 0
fi

if [ $install_realtime -eq -1 ]; then
    # real-time is not installed yet
    echo "Do you also want to use real-time scanning? (Note this feature requires a plan that supports real-time scanning.)"
    echo ""
    echo -n "Install? [y/N] "
    read -rn 1 realtime

    if [ "$realtime" != "" ]; then
        echo ""
    fi

    if [ "$realtime" == "y" ] || [ "realtime" == "Y" ]; then
        install_realtime=1
    else
        install_realtime=0
    fi

    echo ""
    echo "Note: If you want to avoid this question during future installations, you can supply"
    echo "            the --realtime option to this script, e.g.:"
    echo ""
    echo "            /bin/bash -e $0 --realtime=[yes/no]"
    echo ""

    sleep 2
fi

if [ $install_realtime -eq 1 ]; then
    if [ -e /etc/redhat-release ]; then 
        yum -y install patchman-client-realtime
    elif [ -e /etc/debian_version ]; then
        apt-get install -y patchman-client-realtime
    fi

        
    if is_package_installed patchman-client-realtime; then
        echo "Installation of real-time scanning finished."
        echo ""
        echo "Remember to verify that real-time scanning is enabled for this server group in the Patchman Portal."
    else
        echo "An error occurred while installing real-time scanning. Please contact support@patchman.co."
        exit 0
    fi
fi

echo ""
