#! /bin/bash

zomp_dir="$HOME"/zomp
bin="$HOME"/bin

cd "$(dirname $(realpath $0))"
chmod +x uninstall

if erl=$(command -v erl)
  then
    echo "Erlang found at $erl"
  else
    echo "Could not find an Erlang installation!"
    echo "Erlang must be installed and available in \$PATH to proceed."
    exit 95
fi

if [ -d "$zomp_dir" ]
  then
    echo "Installation directory $zomp_dir already exists. Aborting."
    exit 17
fi

if [ ! -d "$bin" ]
  then
    echo "$bin does not exist. Creating it."
    mkdir "$bin"
fi

if [[ ":$PATH:" == *":$bin:"* ]]
  then
    echo "$bin was found in \$PATH. Good to go."
  else
    echo "$bin was not found in \$PATH. Adding it."
    export PATH="$bin:$PATH"
fi

for rc in ~/.bashrc ~/.bash_profile ~/.profile ~/.zshrc ~/.zprofile ~/.zshenv
do
    if [[ -f "$rc" ]]
    then
        if ! grep -q "export PATH=.*[:=]$HOME/bin[:$]" "$rc"
        then
            # This actually fixes the stupid newline thing
            echo -e "\n"'export PATH="$HOME/bin:$PATH"' >> "$rc"
        fi
    else
        touch "$rc"
        echo -e 'export PATH="$HOME/bin:$PATH"' >> "$rc"
    fi
done

cp -r zomp "$zomp_dir"
cp unix/zx "$zomp_dir"
cp unix/zxh "$zomp_dir"
cp README.md "$zomp_dir"
cp LICENSE "$zomp_dir"
cp uninstall "$zomp_dir"
ln -s "$zomp_dir"/zx "$bin"/zx
ln -s "$zomp_dir"/zxh "$bin"/zxh

if zx_link=$(command -v zx)
  then
    echo "zx found at $zx_link. Checking for upgrade."
    echo "Running \`zx upgrade\`..."
    zx upgrade
  else
    echo "zx is not yet in \$PATH."
    echo "Add zx's location ($HOME/bin) to \$PATH run \`zx upgrade\`."
fi
