#!/bin/bash
pwsh_version="7.0.3"
pwsh_path=$(which pwsh)
deb_root="staging/powershell"

rm $deb_root -rd;
mkdir $deb_root/usr/bin -p
install_path="$deb_root/opt/microsoft/powershell/$pwsh_version"
mkdir $install_path -p 


echo "Detecting architecture"
if [ -x "$(command -v dpkg)" ] ; then
	  architecture=$(dpkg --print-architecture)
fi
case $(uname -m) in
    i386)   architecture="386" ;;
    i686)   architecture="386" ;;
    x86_64) architecture="x64" ;;
    x86) architecture="x86" ;;
esac
echo "System architecture is $architecture"

file="powershell-$pwsh_version-linux-$architecture.tar.gz"
link_path="https://github.com/PowerShell/PowerShell/releases/download/v$pwsh_version/$file"

echo "Downloading powershell v$pwsh_version from $link_path"
if ! test -e "$file"; then
  wget "$link_path"
fi

echo "Installing to $install_path"
# Make folder to put powershell
mkdir -p "$install_path"

# Unpack the tar.gz file
tar -xzf "./$file" -C "$install_path"
rm $file
ln -s "/opt/microsoft/powershell/$pwsh_version/pwsh" $deb_root/usr/bin/pwsh

mkdir -p "$deb_root/DEBIAN"
echo "Package: powershell" | tee "$deb_root/DEBIAN/control"
echo "Version: $pwsh_version-$(date +'%Y%m%d')"| tee "$deb_root/DEBIAN/control" -a
echo "Architecture: $(dpkg --print-architecture)"| tee "$deb_root/DEBIAN/control" -a
echo "Essential: no"| tee "$deb_root/DEBIAN/control" -a
echo "Section: web"| tee "$deb_root/DEBIAN/control" -a
echo "Priority: optional"| tee "$deb_root/DEBIAN/control" -a
echo "Depends: python3,libunwind8,less,locales,ca-certificates,libssl1.1,libc6,libgcc1,libgssapi-krb5-2,liblttng-ust0,libstdc++6,zlib1g,curl,gnupg,apt-transport-https"| tee "$deb_root/DEBIAN/control" -a
echo "Maintainer: $(whoami)"| tee "$deb_root/DEBIAN/control" -a
echo "Installed-Size: $(du -s $deb_root | cut -d s -f 1)"| tee "$deb_root/DEBIAN/control" -a
echo "Description: Dummy"| tee "$deb_root/DEBIAN/control" -a
