#!/usr/bin/env bash

select_archive_format() {
  format=$(printf "zip\n7z" | fzf --ansi --border=block --margin=0,35% --no-info --height=7 --prompt="Select archive format: ")
  if [ -z "${format}" ]; then
    printf "No format selected.\n" >&2
    return 1
  fi
  printf "%s" "${format}"
}

prompt_filename() {
  filename=$(: | fzf --disabled --print-query --border=block --margin=0,25% --no-info --height=2 --prompt="Archive Filename (without extension): ")
  if [ -z "${filename}" ]; then
    printf "Filename cannot be empty.\n" >&2
    return 1
  fi
  printf "%s" "${filename}"
}

get_password() {
  password1=$(dmenupass "Enter encryption password:")
  password2=$(dmenupass "Confirm encryption password:")

  if [ "${password1}" != "${password2}" ]; then
    printf "Passwords do not match. Try again.\n" >&2
    return 1
  fi

  printf "%s" "${password1}"
}

prompt_encryption() {
  choice=$(printf "No\nYes" | fzf --ansi --border=block --margin=0,35% --no-info --height=7 --prompt="Encrypt archive with AES-256? ")
  if [ "${choice}" = "Yes" ]; then
    password=$(get_password) || return 1
    encryption_opts="-p${password}"
  else
    encryption_opts=""
  fi
  printf "%s" "${encryption_opts}"
}

prompt_share() {
  choice=$(printf "No\nYes" | fzf --ansi --border=block --margin=0,35% --no-info --height=7 --prompt="Share archive? ")
  [ "${choice}" = "Yes" ] && printf "Yes" || printf "No"
}

main() {

  if [ $# -eq 0 ]; then
    printf "Usage: %s <file/folder>...\n" "$(basename "$0")" >&2
    exit 1
  fi

  filename=$(prompt_filename) || exit 1
  format=$(select_archive_format) || exit 1
  password_flag=$(prompt_encryption) || exit 1
  share_choice=$(prompt_share)

  case "${format}" in
  zip)
    extension="zip"
    archive_type="-tzip"
    encryption_opts="${password_flag} -mem=AES256"
    ;;
  7z)
    extension="7z"
    archive_type="-t7z"
    encryption_opts="${password_flag} -mhe=on"
    ;;
  *)
    printf "Invalid format selected.\n" >&2
    return 1
    ;;
  esac

  archive_name="${filename}.${extension}"
  7z a "${archive_name}" "${archive_type}" "${encryption_opts}" "$@" || {
    printf "Error creating %s archive.\n" "${format}" >&2
    return 1
  }

  if [ "${share_choice}" = "Yes" ]; then
    fileshare "${archive_name}" || {
      printf "Error sharing archive.\n" >&2
      return 1
    }
  fi

  printf "Archive %s created successfully.\n" "${archive_name}"
}

main "$@"
