#!/bin/sh
set -e

# ---------------------------------------------------------------------
# Post-installation script for PyCharm CE
# Downloads and extracts the tarball into /opt/pycharm-ce
# ---------------------------------------------------------------------

version="@VERSION@"
upstream_version=$(echo "$version" | sed 's/^.*://; s/~[^~-]*$//')
file="pycharm-${upstream_version}.tar.gz"
url="https://download.jetbrains.com/python/${file}"
download_path="/tmp/pycharm-ce-${upstream_version}.tar.gz"
optdir="/opt/pycharm-ce"

# Run only during configuration
if [ "$1" = "configure" ]; then
    # Delete target directory to ensure, upgrading to new version works correctly 
    if [ -d "$optdir" ]; then
        rm -rf "$optdir"
    fi
    # Ensure target directory exists
    mkdir -p "$optdir"

    # Download tarball if not already present
    [ -f "${download_path}" ] && rm -rf "${download_path}"

    wget --show-progress -O "${download_path}" "$url"

    # Extract tarball
    echo "Extracting PyCharm ${upstream_version}..."
    tar -xzf "${download_path}" -C "$optdir" --strip-components=1
    
    # Removing Tarball
    rm -f "${download_path}"
fi
