#!/usr/bin/env sh

# This script is based on documentation found here:
# https://github.com/powershell/powershell
#
# danielbowling424@msn.com
# http://www.swagg.net
#
# Copyright 2020 Daniel Bowling, Reston, Virginia, USA
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# Set -e flag to exit upon error
set -e

# Are we running as root?
if [ "`whoami`" != root ]; then
    echo "$0: Please run as root"
    exit 64
fi

# Import distro info or die tryin
if [ -f /etc/lsb-release ]; then
    . /etc/lsb-release
else
    echo '/etc/lsb-release not found!'
    exit 65
fi

# Let's do some sanity checks
while [ : ]; do
    # Are we running Ubuntu?
    case $DISTRIB_ID in
        Ubuntu)
            ;;
        *)
            echo "$0: Distro $DISTRIB_ID detected, must be Ubuntu compatible"
            ;;
    esac

    # Is it a supported version?
    case $DISTRIB_RELEASE in
        16.04|18.04)
            echo "$0: Ubuntu LTS $DISTRIB_RELEASE detected"
            ;;
        *.04)
            echo "$0: Script not tested with this LTS version"
            ;;
        *)
            echo "$0: Powershell is only supported by LTS version"
            ;;
    esac

    # User wants to proceed?
    printf "Continue? (Y/n) "
    read -r answer
    case $answer in
        N*|n*)
            exit 66
            ;;
        *)
            break
            ;;
    esac
done

# Download the Microsoft repository GPG keys
wget -q https://packages.microsoft.com/config/ubuntu/"$DISTRIB_RELEASE"/packages-microsoft-prod.deb

# Register the Microsoft repository GPG keys
dpkg -i packages-microsoft-prod.deb

# Update the list of products
apt-get update

# Only 18.04 should require this step
if [ "$DISTRIB_RELEASE" = 18.04 ]; then
    # Enable the "universe" repositories
    add-apt-repository universe
fi

# Install PowerShell
apt-get install -y powershell

echo "$0: DONE. Run \`pwsh\` to start Powershell"
