#!/usr/bin/env bash

set -e

printf "Oluşturmak istediğiniz klasör yolunu girin (ör: styles/yeniTema): "
IFS= read -r TARGET_DIR

if [ -z "$TARGET_DIR" ]; then
  echo "Hata: Klasör adı boş olamaz."
  exit 1
fi

# Klasörü oluştur
mkdir -p "$TARGET_DIR"
mkdir -p "$TARGET_DIR/mobile"

create_file() {
  FILE_PATH="$1"
  CONTENT="$2"
  # shellcheck disable=SC2016
  printf "%s" "$CONTENT" > "$FILE_PATH"
  echo "Yazıldı: $FILE_PATH"
}

# LESS dosya içerikleri
CONTENT_MAIN_TO_CUSTOM='// main: custom.less
'

CONTENT_VARIABLES='// main: custom.less

@custom: #e1282b;'

CONTENT_CUSTOM='// compress: true

@import '\''variables.less'\'';
@import '\''nav.less'\'';
@import '\''footer.less'\'';
@import '\''body.less'\'';

.custom {
    background-color: @custom;
}'

BAR_CHAR='|'
EMPTY_CHAR=' '

fatal() {
  echo '[FATAL]' "$@" >&2
  exit 1
}

progress_bar() {
  local current=$1
  local len=$2

  local perc_done=$((current * 100 / len))
  local suffix=" $current/$len ($perc_done%)"

  local length=$((COLUMNS - ${#suffix} - 2))
  (( length < 10 )) && length=10
  local num_bars=$((perc_done * length / 100))

  local i
  local s='['
  for ((i = 0; i < num_bars; i++)); do s+=$BAR_CHAR; done
  for ((i = num_bars; i < length; i++)); do s+=$EMPTY_CHAR; done
  s+=']'
  s+=$suffix

  printf '\e7'
    printf '\e[%d;%dH' "$LINES" 0
    printf '\e[0K'
    printf '%s' "$s"
  printf '\e8'
}

init_term() {
  printf '\n'
  printf '\e7'
    printf '\e[%d;%dr' 0 "$((LINES - 1))"
  printf '\e8'
  printf '\e[1A'
}

deinit_term() {
  printf '\e7'
    printf '\e[%d;%dr' 0 "$LINES"
    printf '\e[%d;%dH' "$LINES" 0
    printf '\e[0K'
  printf '\e8'
}

shopt -s checkwinsize
(:) # LINES/COLUMNS güncellemesi için

trap deinit_term EXIT
trap init_term WINCH
init_term

TOTAL_STEPS=10
STEP=0
# Adımlar arası gecikme (saniye). Çevre değişkeni ile değiştirilebilir: DELAY=0.1 ./script
DELAY=${DELAY:-0.08}

# Dosyaları oluştur (root)
create_file "$TARGET_DIR/body.less" "$CONTENT_MAIN_TO_CUSTOM"; STEP=$((STEP+1)); progress_bar "$STEP" "$TOTAL_STEPS"; sleep "$DELAY"
create_file "$TARGET_DIR/nav.less" "$CONTENT_MAIN_TO_CUSTOM"; STEP=$((STEP+1)); progress_bar "$STEP" "$TOTAL_STEPS"; sleep "$DELAY"
create_file "$TARGET_DIR/footer.less" "$CONTENT_MAIN_TO_CUSTOM"; STEP=$((STEP+1)); progress_bar "$STEP" "$TOTAL_STEPS"; sleep "$DELAY"
create_file "$TARGET_DIR/variables.less" "$CONTENT_VARIABLES"; STEP=$((STEP+1)); progress_bar "$STEP" "$TOTAL_STEPS"; sleep "$DELAY"
create_file "$TARGET_DIR/custom.less" "$CONTENT_CUSTOM"; STEP=$((STEP+1)); progress_bar "$STEP" "$TOTAL_STEPS"; sleep "$DELAY"

# Mobile klasörüne kopyala (üzerine yazar)
for f in body.less nav.less footer.less variables.less custom.less; do
  cp -f "$TARGET_DIR/$f" "$TARGET_DIR/mobile/$f"
  echo "Kopyalandı: $TARGET_DIR/$f -> $TARGET_DIR/mobile/$f"
  STEP=$((STEP+1)); progress_bar "$STEP" "$TOTAL_STEPS"; sleep "$DELAY"
done

printf "\n"

echo "İşlem tamamlandı. Klasör: $TARGET_DIR ve $TARGET_DIR/mobile"


