#!/bin/sh

post_upgrade() {
  if [ "$(vercmp 39-5 "$2")" -eq 1 ]; then
    printf '==> Check if we should port MODULES to new array format in /etc/mkinitcpio.conf.\n'
    if [[ $(sed -n '/^MODULES=".*"/p' /etc/mkinitcpio.conf) ]]; then
      printf '  -> Old string format found. Changing to array format.\n'
      sed -Ei 's/^MODULES="(.*)"/MODULES=\(\1\)/g' /etc/mkinitcpio.conf
    else
      printf '  -> No string format found. No change.\n'
    fi

    printf '==> Check if we should port BINARIES to new array format in /etc/mkinitcpio.conf.\n'
    if [[ $(sed -n '/^BINARIES=".*"/p' /etc/mkinitcpio.conf) ]]; then
      printf '  -> Old string format found. Changing to array format.\n'
      sed -Ei 's/^BINARIES="(.*)"/BINARIES=\(\1\)/g' /etc/mkinitcpio.conf
    else
      printf '  -> No string format found. No change.\n'
    fi

    printf '==> Check if we should port FILES to new array format in /etc/mkinitcpio.conf.\n'
    if [[ $(sed -n '/^FILES=".*"/p' /etc/mkinitcpio.conf) ]]; then
      printf '  -> Old string format found. Changing to array format.\n'
      sed -Ei 's/^FILES="(.*)"/FILES=\(\1\)/g' /etc/mkinitcpio.conf
    else
      printf '  -> No string format found. No change.\n'
    fi

    printf '==> Check if we should port HOOKS to new array format in /etc/mkinitcpio.conf.\n'
    if [[ $(sed -n '/^HOOKS=".*"/p' /etc/mkinitcpio.conf) ]]; then
      printf '  -> Old string format found. Changing to array format.\n'
      sed -Ei 's/^HOOKS="(.*)"/HOOKS=\(\1\)/g' /etc/mkinitcpio.conf
    else
      printf '  -> No string format found. No change.\n'
    fi
  fi

  if [ "$(vercmp 39-5 "$2")" -eq 1 ]; then
    printf '==> Check if we need to add "kms" to hooks in /etc/mkinitcpio.conf.\n'

    if [[ $(sed -n '/^HOOKS=.*\bkms\b.*/p' /etc/mkinitcpio.conf) ]]; then
      printf '  -> "kms" hook already exists. Doing nothing.\n'
    else
      printf '  -> "kms" hook does not exist yet. Adding it to the HOOKS line.\n'

      if [[ $(sed -n '/^HOOKS=.*\bmodconf\b.*/p' /etc/mkinitcpio.conf) ]]; then
        printf '  -> Adding "kms" hook after "modconf" hook.\n'
        sed -Ei 's/^HOOKS=(.*\bmodconf\b)(.*)/HOOKS=\1 kms\2/g' /etc/mkinitcpio.conf
      else
        printf '  -> Did not find "modconf" hook to place after. No change.\n'
      fi
    fi
  fi
}
