diff --git a/dev-tools/packaging/templates/linux/postinstall.sh.tmpl b/dev-tools/packaging/templates/linux/postinstall.sh.tmpl index 083ebb91060..d96f21a8629 100644 --- a/dev-tools/packaging/templates/linux/postinstall.sh.tmpl +++ b/dev-tools/packaging/templates/linux/postinstall.sh.tmpl @@ -3,16 +3,26 @@ set -e symlink="/usr/share/elastic-agent/bin/elastic-agent" -old_agent_dir="$( dirname "$(readlink -f -- "$symlink")" )" +old_agent_dir="" + +# check if $symlink exists for the previous install +# and derive the old agent directory +if test -L "$symlink"; then + resolved_symlink="$(readlink -f -- "$symlink")" + # check if it is resolved to non empty string + if ! [ -z "$resolved_symlink" ]; then + old_agent_dir="$( dirname "$resolved_symlink" )" + fi +fi commit_hash="{{ commit_short }}" -yml_path="$old_agent_dir/state.yml" -enc_path="$old_agent_dir/state.enc" +new_agent_dir="/var/lib/elastic-agent/data/elastic-agent-$commit_hash" -new_agent_dir="$( dirname "$old_agent_dir")/elastic-agent-$commit_hash" - -if ! [[ "$old_agent_dir" -ef "$new_agent_dir" ]]; then +# copy the state files if there was a previous agent install +if ! [ -z "$old_agent_dir" ] && ! [ "$old_agent_dir" -ef "$new_agent_dir" ]; then + yml_path="$old_agent_dir/state.yml" + enc_path="$old_agent_dir/state.enc" echo "migrate state from $old_agent_dir to $new_agent_dir" if test -f "$yml_path"; then @@ -24,15 +34,17 @@ if ! [[ "$old_agent_dir" -ef "$new_agent_dir" ]]; then echo "found "$enc_path", copy to "$new_agent_dir"." cp "$enc_path" "$new_agent_dir" fi +fi - if test -f "$symlink"; then - echo "found symlink $symlink, unlink" - unlink "$symlink" - fi - - echo "create symlink "$symlink" to "$new_agent_dir/elastic-agent"" - ln -s "$new_agent_dir/elastic-agent" "$symlink" +# delete symlink if exists +if test -L "$symlink"; then + echo "found symlink $symlink, unlink" + unlink "$symlink" fi +# create symlink to the new agent +echo "create symlink "$symlink" to "$new_agent_dir/elastic-agent"" +ln -s "$new_agent_dir/elastic-agent" "$symlink" + systemctl daemon-reload 2> /dev/null exit 0